LLaMA Implementation
# What does this PR do?

Implementation of LLaMA models (https://arxiv.org/abs/2302.13971). Model weights can be requested [here](https://docs.google.com/forms/d/e/1FAIpQLSfqNECQnMkycAp2jP4Z9TFX0cGR4uf7b_fBxjY_OjhJILlKGA/viewform). Weight conversion script is included.

Weights conversion can be run via:

```bash
python src/transformers/models/llama/convert_llama_weights_to_hf.py \
    --input_dir /path/to/downloaded/llama/weights \
    --model_size 7B \
    --output_dir /output/path
```

Models can then be loaded via:

```python
tokenizer = transformers.LLaMATokenizer.from_pretrained("/output/path/tokenizer/")
model = transformers.LLaMAForCausalLM.from_pretrained("/output/path/llama-7b/")
```

Example:

```bash
batch = tokenizer(
    "The primary use of LLaMA is research on large language models, including",
    return_tensors="pt", 
    add_special_tokens=False
)
batch = {k: v.cuda() for k, v in batch.items()}
generated = model.generate(batch["input_ids"], max_length=100)
print(tokenizer.decode(generated[0]))
```

<!--
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 https://github.com/huggingface/transformers/issues/21796

## 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?
- [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.
- [x] 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 @younesbelkada

<!-- 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: @sgugger

Integrations:

- deepspeed: HF Trainer: @stas00, Accelerate: @pacman100
- ray/raytune: @richardliaw, @amogkam

Documentation: @sgugger, @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: @sgugger
- TensorFlow: @Rocketknight1

 -->

does this work with int8?<|||||>> does this work with int8?

No idea! I haven't messed with int8 too much myself. It ought to be compatible with whatever is already supported in the HF models.<|||||>nice work! thanks for the upload and I hope it gets pulled<|||||>_The documentation is not available anymore as the PR was closed or merged._<|||||>It looks like the tests which are currently failing are unrelated to the LLaMA code, so this should be good to review/use.

If folks can try it out (particularly with the larger, sharded models) and see if there are any issues, that will be helpful!<|||||>> It looks like the tests which are currently failing are unrelated to the LLaMA code, so this should be good to review/use.
> 
> If folks can try it out (particularly with the larger, sharded models) and see if there are any issues, that will be helpful!

At lest the convert script seems to work fine. I was able to convert 7B to 30B. I do not have enough ram to convert 65B.<|||||>Great work. thanks for putting this together<|||||>After replacing transformers from Kobold with this PR I am able to load the shards as expected. Just I cant generate anything because Kobold still needs some changes.
![image](https://user-images.githubusercontent.com/7269941/222938895-2e8b9d71-6a88-417d-b7ed-14d8216d2ef4.png)
<|||||>> > does this work with int8?
> 
> No idea! I haven't messed with int8 too much myself. It ought to be compatible with whatever is already supported in the HF models.

Int8 seems not working but float16 is fine, in my hasty put-together test at https://github.com/zsc/llama_infer . Please throw a comment in case you find something!<|||||>@zphang  I'm not able to get something like  `tokenizer = AutoTokenizer.from_pretrained("/data/llama/hf/7b/tokenizer/")` to work. Is this intentional or just leaving AutoTokenizer for future work?<|||||>> @zphang I'm not able to get something like `tokenizer = AutoTokenizer.from_pretrained("/data/llama/hf/7b/tokenizer/")` to work. Is this intentional or just leaving AutoTokenizer for future work?

What issue are you having / what is the error?<|||||>I have tested the code and these are my findings:

1. The conversion script works.
2. Loading the model works.
3. Loading the tokenizer with `transformers.LLaMATokenizer.from_pretrained` works.
4. Loading the tokenizer with `AutoTokenizer.from_pretrained` does not work and generates this error:

```
OSError: /tmp/converted/tokenizer/ does not appear to have a file named config.json. Checkout
'https://huggingface.co//tmp/converted/tokenizer//None' for available files.

```

5. The generated text seems to be incoherent. If I try these default values for the generation parameters:

```
model.generate(input_ids, eos_token_id=2, do_sample=True, temperature=1, top_p=1, typical_p=1, repetition_penalty=1, top_k=50, min_length=0, no_repeat_ngram_size=0, num_beams=1, penalty_alpha=0, length_penalty=1, early_stopping=False, max_new_tokens=200).cuda()
```

with this prompt:

```
Common sense questions and answers

Question: What color is the sky?
Factual answer:
```

I get

```
Common sense questions and answers

Question: What color is the sky?
Factual answer: Tags: python, django, django-models

Question: Using Django with multiple databases

I am attempting to use django with multiple databases, and I have the following code:

\begin{code}
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': ':memory:',
    },
    'db_one': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'db_one',
    },
    'db_two': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'db_two',
    },
}
```

It seems to me that prompts are being completely ignored.

6. Loading in 8-bit mode with `load_in_8bit=True` works.<|||||>This is OK: `tokenizer = transformers.LLaMATokenizer.from_pretrained("/data/llama/hf/7b/tokenizer/")`

If using `tokenizer = AutoTokenizer.from_pretrained("/data/llama/hf/7b/tokenizer/"` then it will complain no "config.json". 
```
OSError: /data/llama/hf/7b/tokenizer/ does not appear to have a file named config.json. Checkout 
'https://huggingface.co//data/llama/hf/7b/tokenizer//None' for available files.
```

I then hacked by softlinking `/data/llama/hf/7b/tokenizer/special_tokens_map.json` to `/data/llama/hf/7b/tokenizer/config.json` and it works. So maybe just rename?

Anyway, can now happily play with LLaMA in Hugging Face world and thanks for the great work!<|||||>Thanks for the comments. Looks like the saved tokenizer doesn't work for `AutoTokenizer` but works if you directly instantiate from `LLaMATokenizer`. Maybe one of the HF folks can chime in on the best way to address that.

> The generated text seems to be incoherent. If I try these default values for the generation parameters:

Can you check the input_ids you're using to generate? The tokenizer currently adds both BOS and EOS tokens by default, and an EOS might cause the model to ignore your prompt.

Perhaps I can set EOS to not be added by default so it operates closer to expected behavior.<|||||>For this prompt:

```
'Common sense questions and answers\n\nQuestion: What color is the sky?\nFactual answer:'
```

these are the input_ids:

```
tensor([[    1, 13103,  4060,  5155,   322,  6089,    13,    13, 16492, 29901,
          1724,  2927,   338,   278, 14744, 29973,    13, 29943, 19304,  1234,
         29901,     2]], device='cuda:0')
```

I do not know how to interpret these numbers, but if there is an EOS token in that tensor and that token is causing the text generation to derail, changing that default would be valuable.<|||||>1 is BOS and 2 is EOS. Can you try without the last input id?

I also added an example in my PR message.<|||||>I confirm that doing this 
```
    input_ids = input_ids[:, :-1]

```

to remove the last input id before calling `model.generate(...)` causes the text generation to become coherent:

```
Common sense questions and answers

Question: What color is the sky?
Factual answer: The sky is blue. The sky is blue, and it is a fact that it is blue. The sky is indisputably blue.

```<|||||>Added a commit that should fix the tokenizer issues, and not add BOS and EOS by default.<|||||>Awesome, I confirm that the text generation is coherent by default now.

I still cannot load the tokenizer with `AutoTokenizer.from_pretrained`. The error has now changed to this:

```
  File "/tmp/transformers/src/transformers/models/auto/tokenization_auto.py", line 694, in from_pretrained
    tokenizer_class_py, tokenizer_class_fast = TOKENIZER_MAPPING[type(config)]
  File "/tmp/transformers/src/transformers/models/auto/auto_factory.py", line 610, in __getitem__
    raise KeyError(key)
KeyError: <class 'transformers.models.llama.configuration_llama.LLaMAConfig'>

```<|||||>> > does this work with int8?
> 
> No idea! I haven't messed with int8 too much myself. It ought to be compatible with whatever is already supported in the HF models.

After the fix with EOS, int8 (bitsandbytes) looks decent. Example in https://github.com/zsc/llama_infer/blob/main/README.md<|||||>After https://github.com/huggingface/transformers/pull/21955/commits/459e2ac9f551650ced58deb1c65f06c3d483d606, `AutoTokenizer.from_pretrained` now works as expected.
<|||||>KoboldAI now works<|||||>I'd like to see a more memory-efficient conversion script, the current version loads everything into system memory which makes converting the 30B and 65B variants challenging on some systems<|||||>Yes, this is a quick and dirty version that loads everything into memory.
One issue is that the way the weights are sharded (for tensor parallelism) is orthogonal to the way that HF shards the weights (by layer). So either we have to load everything in at once, or we have to load/write multiple times. The latter would be slower but useful for folks with less memory.<|||||>Has anyone tested loading 65B with `accelerate` to load on multiple GPUs?<|||||>I can't load the 7B model to cuda with one A4000
should I just change the gpu?
<|||||>I'm observing some strange behavior with the tokenizer when encoding sequences beginning with a newline:
```
>>> t = AutoTokenizer.from_pretrained("llama_hf/tokenizer")
>>> res = t.encode("\nYou:")
>>> res
[29871, 13, 3492, 29901]
>>> t.decode(res)
'You:'
```

The newline seems to get lost somewhere along the way.

EDIT: Looking into this, it seems it might be the expected behavior of `sentencepiece`.<|||||>> Has anyone tested loading 65B with `accelerate` to load on multiple GPUs?

||fp16|int8(bitsandbytes)|
|--|--|--|
|V100|OK, 5xV100|Bad results, short generated sequences|
|A100|OK, 6xA100 when using "auto"|OK, 3xA100|

Yes, I currently have a 65B fp16 model running on 6xV100 now (5X should be enough). My working code is at https://github.com/zsc/llama_infer/ . If there are CUDA OOM due to bad distribution of weights among cards, one thing worth trying is tweaking the device_map (`accelerate` seems to only counts weights when enforcing the memory cap in device_map, so there is an art for setting custom cap a little lower for every card, especially card 0).

Strangely, int8 (LLM.int8 to be specific) for 65B model works like a charm on A100, but leads to bad results on V100 with abnormally short generated sequences.<|||||>> Strangely, int8 (LLM.int8 to be specific) for 65B model works like a charm on A100, but leads to bad results on V100 with abnormally short generated sequences.

I will have a look at this later next week. The V100 takes a different code path than the A100 because the V100 does not support Int8 tensor cores. I think that is the issue here. We will soon publish FP4 inference which should be more universal and easier to use.<|||||>Jumping on @thomasw21 comment, we sadly cannot accept any code licensed GPLv3 as it would taint the whole Transformers library under that license. This means that the modeling code should be copied from GPT-NeoX whenever possible (with Copied from statements) since I believe that this model is very close to it and that you should be super familiar with it @zphang ;-) , and that no parts of the modeling code should be copy-pasted from the original Llama code.

We also cannot attribute Copyright to Meta-AI /Meta in all those files, as attributing that copyright would admit the code in the PR is based on theirs and thus get us back to the license problem.<|||||>I tried quantizing LLaMa using [GPTQ](https://arxiv.org/abs/2210.17323).
I've confirmed that 4 or 3 bit quantization works well, at least on LLaMa 7b.
| Model([LLaMa-7B](https://arxiv.org/abs/2302.13971))      | Bits | group-size | Wikitext2 |   PTB     |    C4   |
| ---------                                                | ---- | ---------- | --------- | --------- | ------- |
| FP16                                                     |  16  |     -      |    5.67   |    8.79   |   7.05  | 
| RTN                                                      |  4   |     -      |    6.28   |    9.68   |   7.70  | 
| [GPTQ](https://arxiv.org/abs/2210.17323)                 |  4   |    64      |    **6.16**   |    **9.66**   |   **7.52**  | 
| RTN                                                      |  3   |     -      |    25.66   |    61.25   |   28.19  | 
| [GPTQ](https://arxiv.org/abs/2210.17323)                 |  3   |    64      |    **12.24**   |    **16.77**   |   **9.55**  | 

I have released the [code](https://github.com/qwopqwop200/GPTQ-for-LLaMa) for this.
<|||||>Running into an issue with the following code
```
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("models/facebook_LLaMA-7b")
output = [[v] for k, v in tokenizer.get_vocab().items() if any(c in str(k) for c in "<>[]")]
debug_output = tokenizer.batch_decode(output)
print(debug_output)
```

This is supposed to only print tokens that are including one of the <>[] characters, but I am getting a wide range back at the beginning causing our code to effect way to many tokens. This includes tokens that are blatantly false such as every singular letter of the alphabet.
Is this to be expected with the kind of tokenizer that is used and do we have to find an alternative implementation or is something going wrong here on a deeper level?

If I try the same thing with a tokenizer from the usual models we run such as the GPT-J tokenizer this code runs properly.<|||||>> I tried quantizing LLaMa using [GPTQ](https://arxiv.org/abs/2210.17323). I've confirmed that 4 or 3 bit quantization works well, at least on LLaMa 7b.
> 
> Model([LLaMa-7B](https://arxiv.org/abs/2302.13971))	Bits	group-size	Wikitext2	PTB	C4
> FP16	16	-	5.67	8.79	7.05
> RTN	4	-	6.28	9.68	7.70
> [GPTQ](https://arxiv.org/abs/2210.17323)	4	64	**6.16**	**9.66**	**7.52**
> RTN	3	-	25.66	61.25	28.19
> [GPTQ](https://arxiv.org/abs/2210.17323)	3	64	**12.24**	**16.77**	**9.55**
> I have released the [code](https://github.com/qwopqwop200/GPTQ-for-LLaMa) for this.

Do you plan to publish 4-bit quantized models on the hub? If not, I'd be more than happy to generate them and push them up.<|||||>> > [GPTQ를](https://arxiv.org/abs/2210.17323) 사용하여 LLaMa를 양자화해 보았습니다 . 적어도 LLaMa 7b에서는 4비트 또는 3비트 양자화가 잘 작동함을 확인했습니다.
> > Model( [LLaMa-7B](https://arxiv.org/abs/2302.13971) ) Bits group-size Wikitext2 PTB C4 [FP16](https://github.com/qwopqwop200/GPTQ-for-LLaMa) 
> > 16 - 5.67 8.79 7.05 
> > RTN 4 - 
> > 6.28 9.68 7.70 
> > [GPTQ](https://arxiv.org/abs/2210.17323) 	4 64	 **6.16 **	**9.66 **	**7.52** RTN 
> > 3 - 25.66 61.25 28.19 **GPTQ **
> > [3](https://arxiv.org/abs/2210.17323) 	64	 **12.75 ****1** .****	****	****[](https://github.com/qwopqwop200/GPTQ-for-LLaMa)
> 
> 허브에 4비트 양자화 모델을 게시할 계획입니까? 그렇지 않다면 기꺼이 생성하고 밀어 올릴 것입니다.

There are no plans to publish a 4-bit quantization model yet.
And to get advantages in speed and memory, you need to change and use dedicated 3-bit CUDA Kernels.
I haven't even tested 3-bit CUDA Kernels yet.<|||||>Maybe this issure need to be fixed?

the  [llama-int8](https://github.com/tloen/llama-int8)  can works.

but this

```
from  transformers import LLaMaForCausalLM,LLaMaPreTrainedModel
model = LLaMaForCausalLM.from_pretrained("Z:/LLaMA/llama-7b-hf")
```

errors:

File [G:\pythons\huggingface\transformers\src\transformers\modeling_utils.py:2632](file:///G:/pythons/huggingface/transformers/src/transformers/modeling_utils.py:2632), in PreTrainedModel.from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs)
   2622     if dtype_orig is not None:
   2623         torch.set_default_dtype(dtype_orig)
   2625     (
   2626         model,
   2627         missing_keys,
   2628         unexpected_keys,
   2629         mismatched_keys,
   2630         offload_index,
   2631         error_msgs,
-> 2632     ) = cls._load_pretrained_model(
   2633         model,
   2634         state_dict,
   2635         loaded_state_dict_keys,  # XXX: rename?
   2636         resolved_archive_file,
   2637         pretrained_model_name_or_path,
   2638         ignore_mismatched_sizes=ignore_mismatched_sizes,
   2639         sharded_metadata=sharded_metadata,
...
   1268         return modules[name]
-> 1269 raise AttributeError("'{}' object has no attribute '{}'".format(
   1270     type(self).__name__, name))

AttributeError: 'LLaMaLayerNorm' object has no attribute 'bias'
<|||||>#

> Maybe this issure need to be fixed?
> 
> the [llama-int8](https://github.com/tloen/llama-int8) can works.
> 
> but this
> 
> ```
> from  transformers import LLaMaForCausalLM,LLaMaPreTrainedModel
> model = LLaMaForCausalLM.from_pretrained("Z:/LLaMA/llama-7b-hf")
> ```
> 
> errors:
> 
> File G:\pythons\huggingface\transformers\src\transformers\modeling_utils.py:2632, in PreTrainedModel.from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs) 2622 if dtype_orig is not None: 2623 torch.set_default_dtype(dtype_orig) 2625 ( 2626 model, 2627 missing_keys, 2628 unexpected_keys, 2629 mismatched_keys, 2630 offload_index, 2631 error_msgs, -> 2632 ) = cls._load_pretrained_model( 2633 model, 2634 state_dict, 2635 loaded_state_dict_keys, # XXX: rename? 2636 resolved_archive_file, 2637 pretrained_model_name_or_path, 2638 ignore_mismatched_sizes=ignore_mismatched_sizes, 2639 sharded_metadata=sharded_metadata, ... 1268 return modules[name] -> 1269 raise AttributeError("'{}' object has no attribute '{}'".format( 1270 type(self).**name**, name))
> 
> AttributeError: 'LLaMaLayerNorm' object has no attribute 'bias'

I'm not sure how that code even runs, the case doesn't match. You're importing `LLaMaForCausalLM` and the code provides `LLaMAForCausalLM`

Also, where did you pull the model from? Is that the copy from decapoda-research on the hub?<|||||>> Jumping on @thomasw21 comment, we sadly cannot accept any code licensed GPLv3 as it would taint the whole Transformers library under that license. This means that the modeling code should be copied from GPT-NeoX whenever possible (with Copied from statements) since I believe that this model is very close to it and that you should be super familiar with it @zphang ;-) , and that no parts of the modeling code should be copy-pasted from the original Llama code.
> 
> We also cannot attribute Copyright to Meta-AI /Meta in all those files, as attributing that copyright would admit the code in the PR is based on theirs and thus get us back to the license problem.

Note that under Apache 2.0 the correct thing to do is credit _EleutherAI_ with the copyright. I have gone ahead and added the proper copyright headers, including adding a notice informing the reading that the code has been modified from it's original version and where it was adapted from.

**Note that I have not changed the code itself in any way.** If it is currently the case that some of the code is based on the FairSeq implementation that still needs to be removed and rewritten using GPT-NeoX (whether the implementation in this library or the GPT-NeoX library itself) as a reference. However once all GPLv3 licensed code has been removed, the headers I added should be correct.

cc: @zphang @sgugger @thomasw21 for visibility.

It might be worth mentioning this in the documentation of the model, as I anticipate this will cause some people confusion.

> Also, where did you pull the model from? Is that the copy from decapoda-research on the hub?

@zoidbb this PR includes a script for converting the models from their original format to a HF-compliant one.<|||||>@henk717 your code doesn't work for me with any model. I consistently error on the line `debug_output = tokenizer.batch_decode(output)`<|||||>Thanks for your contribution! However, I find that the model usually ends up repeating the same sentence during inference. For example, by running the code below:

```
import transformers
import os

os.environ['CUDA_VISIBLE_DEVICES']='3'

config = transformers.AutoConfig.from_pretrained("./llama-7b-hf/llama-7b")
tokenizer = transformers.AutoTokenizer.from_pretrained("./llama-7b-hf/tokenizer")
model = transformers.AutoModelForCausalLM.from_pretrained("./llama-7b-hf/llama-7b", config=config).cuda()

batch = tokenizer(
    ["The primary use of LLaMA is research on large language models, including "],
    return_tensors="pt"
)

batch = {k: v.cuda() for k, v in batch.items()}
input_ids = batch["input_ids"] # tensor([[1,...]])

generated = model.generate(input_ids, temperature=0.8, top_p=0.95, max_length=256).cuda()
print(tokenizer.decode(generated[0])
```

**the LLaMA-7b-hf output is:**
![1](https://user-images.githubusercontent.com/45878717/223327316-99672393-3d31-4531-bd3c-bc218f1dddd6.png)

**while the original LLaMA(7b) output is (temperature=0.8, top_p=0.95):**
![2](https://user-images.githubusercontent.com/45878717/223327389-5c635bd2-121a-4990-9998-3fbc6f448bd2.png)

Now it seems that the two models are quite different with each other. I wonder if they can output the same sentence, given the same input and parameters?<|||||>after install your branch of llama, i can't import LLaMaTokenizer as below
 ImportError: cannot import name 'LLaMaTokenizer' from 'transformers'

but import LLaMaForCausalLM is successful...
how could this happen?<|||||>Hey all! Great to see that the community is so fired up for this PR 🤗 🔥 ! @zphang thanks a lot for this contribution, don't hesitate to  ping me once this is ready for review,. In the mean time let's all give him some time, as it was never stated that this should already work or compile!
Let's wait until then to report potential issues ! 😉 <|||||>@StellaAthena Fully in line with your change of copyright and also to explicitly mention in the doc page of the model that the code is based on GPT-NeoX and not the original Llama code. This can be put in the usual place we say: "This model was contributed by xxx. The original code can be found [here](yyy)."<|||||>> > Has anyone tested loading 65B with `accelerate` to load on multiple GPUs?
> 
> fp16	int8(bitsandbytes)
> V100	OK, 5xV100	Bad results, short generated sequences
> A100	OK, 6xA100 when using "auto"	OK, 3xA100
> Yes, I currently have a 65B fp16 model running on 6xV100 now (5X should be enough). My working code is at https://github.com/zsc/llama_infer/ . If there are CUDA OOM due to bad distribution of weights among cards, one thing worth trying is tweaking the device_map (`accelerate` seems to only counts weights when enforcing the memory cap in device_map, so there is an art for setting custom cap a little lower for every card, especially card 0).
> 
> Strangely, int8 (LLM.int8 to be specific) for 65B model works like a charm on A100, but leads to bad results on V100 with abnormally short generated sequences.

CC: @zsc 
Just a heads up on the issue with V100 and bitsandbytes, I've encountered a bit weird and may be relevant behavior with long inputs, but relaxing the quantization threshold by `BitsAndBytesConfig(llm_int8_threshold=5.0)` (which I believe is set to 6 by default  according to the [doc](https://huggingface.co/docs/transformers/main/main_classes/quantization)) resolved the issue. Ref: https://github.com/huggingface/transformers/issues/21987
<|||||>@zoidbb  Thank you!!! I'm sorry, the error is the branch of "thomas/llama", not this!<|||||>Heads up to folks already using this PR: I will be pushing some changes today to address the maintainers' feedback that will break compatibility. In particular, I will be making a major change to how the RoPE encodings are computed. Please pull and re-convert the weights when the branch is updated. Sorry for the inconvenience.<|||||>> 

Thanks for the heads up <|||||>As mentioned above, I've pushed an update (previous git hash was: 6a17e7f) that introduces some breaking changes to incorporate the Transformers maintainers' feedback. (There are still some tweaks to go, but nothing that should be breaking from here.)

**Please rerun the weight conversion scripts.**

Major changes:
- Removal of Decoder class
- `add_bos` on by default. `add_eos` is still off.
- Reimplementation of RoPE based on NeoX version. This required a weight permutation (NeoX's RoPE slices the head_dims in half, the Meta implementation interleaves), which is performed in the conversion script. **Note**: the weights are still the same shape, so if you don't rerun the conversion script and only rename the keys, the weights will load but be completely incorrect.

As before, please let me know if you run into any issues, it is great to have this many people trying and testing the implementation.<|||||>Running into issues with the model conversion on the latest update, loading the model fails (On the latest version of the pull request git) and pytorch_model-00033-of-00033 is missing.

Using the custom KoboldAI loader it reports a key error, and using the official HF loader it mentions not all weights could be initialized correctly but does finish the loading process.<|||||>> Running into issues with the model conversion on the latest update, loading the model fails (On the latest version of the pull request git) and pytorch_model-00033-of-00033 is missing.
> 
> Using the custom KoboldAI loader it reports a key error, and using the official HF loader it mentions not all weights could be initialized correctly but does finish the loading process.

Confirmed this is an issue on 7B and 13B both, the last file is missing both from disk and from the index file.<|||||>@zphang you have a typo in the line defining the filename for the last .bin file, you use n_layers instead of n_layers+1. this leads to part 32 being overwritten, instead of part 33 being written (in the case of 7B).<|||||>Hmm now I am a little confused. There is an off-by-one error, but that's it going from 0 to n_layers instead of 1 to n_layers+1. It ought to load just fine though, since it's consistent with the index JSON.

(The +1 is for the embedding layers and final norm)<|||||>Pushed fix for off-by-one naming.<|||||>@zphang now im getting this error:

```
RuntimeError: Failed to import transformers.models.llama.tokenization_t5 because of the following error (look up to see its traceback):
No module named 'transformers.models.llama.tokenization_t5'
```<|||||>Try again now!<|||||>Seems to load, running the new model conversion through its paces. Thanks for your work.<|||||>I am not having any luck yet, my errors remain identical. For context I use AutoModelForCausalLM in the code.<|||||>> I am not having any luck yet, my errors remain identical. For context I use AutoModelForCausalLM in the code.

I'm also using that, and it's working fine. Did you make sure to grab the latest commits and install them? Also you have run the conversion again.<|||||>Late night coding moment, my update script tricked me into thinking it was applying the update but it was only cloning the git instead of applying it (Normally I run a different one that does more that does do that) so my last few attempts used the same code.

The update fixed it, our software also has some regex's to clean up output that were not being applied correctly previously because of an issue I did not manage to track down. On this new iteration of the fork that bug got fixed, so while I do not know what the cause behind that was on the old version I am happy to report the latest version is an improvement for us in functionality.<|||||>The model behaves much better with these latest changes, I was always confused why I either got long elaborate nonsense or really short answers when using it as a chatbot :P Thanks for your work @zphang this is epic.<|||||>Hi thanks for your great work. Can we fine-tune it for now？<|||||>@zphang there seems to be an issue when using generate with `num_return_sequences`.
Running this code:
```python
import torch, os
from transformers import AutoTokenizer, AutoModelForCausalLM
os.environ['CUDA_LAUNCH_BLOCKING'] = "1"

modeldir = "./llama-7b"
tokenizer = AutoTokenizer.from_pretrained(modeldir)
model = AutoModelForCausalLM.from_pretrained(modeldir, torch_dtype=torch.float16).to("cuda")

input_ids = tokenizer('aaaaa', return_tensors="pt").input_ids.to("cuda")
for i in range(100):
    print(i)
    model.generate(input_ids,
                   max_new_tokens=20,
                   do_sample=True,
                   num_return_sequences=4)
```
I get this output:
```
0
1
2
3
4
5
6
7
8
/opt/conda/conda-bld/pytorch_1670525541990/work/aten/src/ATen/native/cuda/Indexing.cu:1088: indexSelectSmallIndex: block: [18,0,0], thread: [96,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1670525541990/work/aten/src/ATen/native/cuda/Indexing.cu:1088: indexSelectSmallIndex: block: [18,0,0], thread: [97,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1670525541990/work/aten/src/ATen/native/cuda/Indexing.cu:1088: indexSelectSmallIndex: block: [18,0,0], thread: [98,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
... a bunch more of those ...
/opt/conda/conda-bld/pytorch_1670525541990/work/aten/src/ATen/native/cuda/Indexing.cu:1088: indexSelectSmallIndex: block: [18,0,0], thread: [126,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1670525541990/work/aten/src/ATen/native/cuda/Indexing.cu:1088: indexSelectSmallIndex: block: [18,0,0], thread: [127,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[1], line 12
     10 for i in range(100):
     11     print(i)
---> 12     model.generate(input_ids,
     13                    max_new_tokens=20,
     14                    do_sample=True,
     15                    num_return_sequences=4)

File [~/mambaforge/envs/reproenv/lib/python3.10/site-packages/torch/autograd/grad_mode.py:27](https://vscode-remote+wsl-002bubuntu.vscode-resource.vscode-cdn.net/home/abstract/projs/pytorch_tests/~/mambaforge/envs/reproenv/lib/python3.10/site-packages/torch/autograd/grad_mode.py:27), in _DecoratorContextManager.__call__..decorate_context(*args, **kwargs)
     24 @functools.wraps(func)
     25 def decorate_context(*args, **kwargs):
     26     with self.clone():
---> 27         return func(*args, **kwargs)

File [~/mambaforge/envs/reproenv/lib/python3.10/site-packages/transformers/generation/utils.py:1452](https://vscode-remote+wsl-002bubuntu.vscode-resource.vscode-cdn.net/home/abstract/projs/pytorch_tests/~/mambaforge/envs/reproenv/lib/python3.10/site-packages/transformers/generation/utils.py:1452), in GenerationMixin.generate(self, inputs, generation_config, logits_processor, stopping_criteria, prefix_allowed_tokens_fn, synced_gpus, **kwargs)
   1444     input_ids, model_kwargs = self._expand_inputs_for_generation(
   1445         input_ids=input_ids,
   1446         expand_size=generation_config.num_return_sequences,
   1447         is_encoder_decoder=self.config.is_encoder_decoder,
   1448         **model_kwargs,
   1449     )
   1451     # 13. run sample
-> 1452     return self.sample(
   1453         input_ids,
   1454         logits_processor=logits_processor,
   1455         logits_warper=logits_warper,
   1456         stopping_criteria=stopping_criteria,
   1457         pad_token_id=generation_config.pad_token_id,
   1458         eos_token_id=generation_config.eos_token_id,
   1459         output_scores=generation_config.output_scores,
   1460         return_dict_in_generate=generation_config.return_dict_in_generate,
   1461         synced_gpus=synced_gpus,
   1462         **model_kwargs,
   1463     )
   1465 elif is_beam_gen_mode:
   1466     if generation_config.num_return_sequences > generation_config.num_beams:

File [~/mambaforge/envs/reproenv/lib/python3.10/site-packages/transformers/generation/utils.py:2468](https://vscode-remote+wsl-002bubuntu.vscode-resource.vscode-cdn.net/home/abstract/projs/pytorch_tests/~/mambaforge/envs/reproenv/lib/python3.10/site-packages/transformers/generation/utils.py:2468), in GenerationMixin.sample(self, input_ids, logits_processor, stopping_criteria, logits_warper, max_length, pad_token_id, eos_token_id, output_attentions, output_hidden_states, output_scores, return_dict_in_generate, synced_gpus, **model_kwargs)
   2465 model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
   2467 # forward pass to get next token
-> 2468 outputs = self(
   2469     **model_inputs,
   2470     return_dict=True,
   2471     output_attentions=output_attentions,
   2472     output_hidden_states=output_hidden_states,
   2473 )
   2475 if synced_gpus and this_peer_finished:
   2476     continue  # don't waste resources running the code we don't need

File [~/mambaforge/envs/reproenv/lib/python3.10/site-packages/torch/nn/modules/module.py:1194](https://vscode-remote+wsl-002bubuntu.vscode-resource.vscode-cdn.net/home/abstract/projs/pytorch_tests/~/mambaforge/envs/reproenv/lib/python3.10/site-packages/torch/nn/modules/module.py:1194), in Module._call_impl(self, *input, **kwargs)
   1190 # If we don't have any hooks, we want to skip the rest of the logic in
   1191 # this function, and just call forward.
   1192 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1193         or _global_forward_hooks or _global_forward_pre_hooks):
-> 1194     return forward_call(*input, **kwargs)
   1195 # Do not call functions when jit is used
   1196 full_backward_hooks, non_full_backward_hooks = [], []

File [~/mambaforge/envs/reproenv/lib/python3.10/site-packages/transformers/models/llama/modeling_llama.py:772](https://vscode-remote+wsl-002bubuntu.vscode-resource.vscode-cdn.net/home/abstract/projs/pytorch_tests/~/mambaforge/envs/reproenv/lib/python3.10/site-packages/transformers/models/llama/modeling_llama.py:772), in LLaMAForCausalLM.forward(self, input_ids, attention_mask, past_key_values, inputs_embeds, labels, use_cache, output_attentions, output_hidden_states, return_dict)
    769 return_dict = return_dict if return_dict is not None else self.config.use_return_dict
    771 # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
--> 772 outputs = self.model(
    773     input_ids=input_ids,
    774     attention_mask=attention_mask,
    775     past_key_values=past_key_values,
    776     inputs_embeds=inputs_embeds,
    777     use_cache=use_cache,
    778     output_attentions=output_attentions,
    779     output_hidden_states=output_hidden_states,
    780     return_dict=return_dict,
    781 )
    783 hidden_states = outputs[0]
    784 logits = self.lm_head(hidden_states)

File [~/mambaforge/envs/reproenv/lib/python3.10/site-packages/torch/nn/modules/module.py:1194](https://vscode-remote+wsl-002bubuntu.vscode-resource.vscode-cdn.net/home/abstract/projs/pytorch_tests/~/mambaforge/envs/reproenv/lib/python3.10/site-packages/torch/nn/modules/module.py:1194), in Module._call_impl(self, *input, **kwargs)
   1190 # If we don't have any hooks, we want to skip the rest of the logic in
   1191 # this function, and just call forward.
   1192 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1193         or _global_forward_hooks or _global_forward_pre_hooks):
-> 1194     return forward_call(*input, **kwargs)
   1195 # Do not call functions when jit is used
   1196 full_backward_hooks, non_full_backward_hooks = [], []

File [~/mambaforge/envs/reproenv/lib/python3.10/site-packages/transformers/models/llama/modeling_llama.py:581](https://vscode-remote+wsl-002bubuntu.vscode-resource.vscode-cdn.net/home/abstract/projs/pytorch_tests/~/mambaforge/envs/reproenv/lib/python3.10/site-packages/transformers/models/llama/modeling_llama.py:581), in LLaMAModel.forward(self, input_ids, attention_mask, past_key_values, inputs_embeds, use_cache, output_attentions, output_hidden_states, return_dict)
    578 if attention_mask is None:
    579     attention_mask = torch.ones(inputs_embeds.shape[:2], dtype=torch.bool, device=inputs_embeds.device)
--> 581 attention_mask = self._prepare_decoder_attention_mask(
    582     attention_mask, input_shape, inputs_embeds, past_key_values_length
    583 )
    585 hidden_states = inputs_embeds
    587 if self.gradient_checkpointing and self.training:

File [~/mambaforge/envs/reproenv/lib/python3.10/site-packages/transformers/models/llama/modeling_llama.py:490](https://vscode-remote+wsl-002bubuntu.vscode-resource.vscode-cdn.net/home/abstract/projs/pytorch_tests/~/mambaforge/envs/reproenv/lib/python3.10/site-packages/transformers/models/llama/modeling_llama.py:490), in LLaMAModel._prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length)
    484     combined_attention_mask = _make_causal_mask(
    485         input_shape, inputs_embeds.dtype, past_key_values_length=past_key_values_length
    486     ).to(inputs_embeds.device)
    488 if attention_mask is not None:
    489     # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
--> 490     expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
    491         inputs_embeds.device
    492     )
    493     combined_attention_mask = (
    494         expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
    495     )
    497 return combined_attention_mask

File [~/mambaforge/envs/reproenv/lib/python3.10/site-packages/transformers/models/llama/modeling_llama.py:77](https://vscode-remote+wsl-002bubuntu.vscode-resource.vscode-cdn.net/home/abstract/projs/pytorch_tests/~/mambaforge/envs/reproenv/lib/python3.10/site-packages/transformers/models/llama/modeling_llama.py:77), in _expand_mask(mask, dtype, tgt_len)
     73 expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
     75 inverted_mask = 1.0 - expanded_mask
---> 77 return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)

RuntimeError: CUDA error: device-side assert triggered
```
My env is
```
mamba create -n reproenv python=3.10 jupyter pip pytorch pytorch-cuda=11.7 -c pytorch -c nvidia
conda activate reproenv
pip install git+https://github.com/zphang/transformers@llama_push sentencepiece
```<|||||>When using the 30B variant I got this error (do_sample=true):
```
File "/secondary/thies/llama/app.py", line 184, in completions
    ids_outputs = model.generate(tok_inputs, max_new_tokens=max_new_tokens, top_p=top_p, top_k=top_k, temperature=temperature, do_sample=True)
  File "/secondary/thies/.virtualenvs/llama/lib/python3.10/site-packages/torch/autograd/grad_mode.py", line 27, in decorate_context
    return func(*args, **kwargs)
  File "/secondary/thies/.virtualenvs/llama/lib/python3.10/site-packages/transformers/generation/utils.py", line 1452, in generate
    return self.sample(
  File "/secondary/thies/.virtualenvs/llama/lib/python3.10/site-packages/transformers/generation/utils.py", line 2504, in sample
    next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
RuntimeError: probability tensor contains either `inf`, `nan` or element < 0
```
7B variant works fine.<|||||>> When using the 30B variant I got this error (do_sample=true):
> 
> ```
> File "/secondary/thies/llama/app.py", line 184, in completions
>     ids_outputs = model.generate(tok_inputs, max_new_tokens=max_new_tokens, top_p=top_p, top_k=top_k, temperature=temperature, do_sample=True)
>   File "/secondary/thies/.virtualenvs/llama/lib/python3.10/site-packages/torch/autograd/grad_mode.py", line 27, in decorate_context
>     return func(*args, **kwargs)
>   File "/secondary/thies/.virtualenvs/llama/lib/python3.10/site-packages/transformers/generation/utils.py", line 1452, in generate
>     return self.sample(
>   File "/secondary/thies/.virtualenvs/llama/lib/python3.10/site-packages/transformers/generation/utils.py", line 2504, in sample
>     next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
> RuntimeError: probability tensor contains either `inf`, `nan` or element < 0
> ```
> 
> 7B variant works fine.

I can also reproduce this when using int8 on my 6900xt<|||||>Also getting 

```
RuntimeError: probability tensor contains either `inf`, `nan` or element < 0`
```
<|||||>I noticed that 6a17e7f3b45454429f2b0405e673dc4aaa695546 version seems to work and fixes the `RuntimeError: probability tensor contains either `inf`, `nan` or element < 0` error.<|||||>I will try to follow up on some of the other reported issues today/tomorrow. I did indeed see an issue with the combined/expanded masks as @BlackSamorez mentioned, although I will need to take a closer look at the fix since there are so many entry points for HF code. 

I also pushed a fix for what I think was causing some of the above issues. Part of it affects the config file, so you should go into the model config.json and set `pad_token_id=0`. With that first, the example code given by @AbstractQbit should run fine now.

I also wrote some very preliminary fine-tuning code https://github.com/zphang/minimal-llama/ if folks are interested in testing it out. It also uses the code from this PR.<|||||>Loading model directly results in warning about not using some weights. Is this expected? Other models (e.g. Bloom) does not have this issue.

```from transformers.models.llama.modeling_llama import LLaMAModel
LLaMAModel.from_pretrained('llama-7b')
```

throws this:

```
Some weights of the model checkpoint at llama-7b were not used when initializing LLaMAModel: ['lm_head.weight']
- This IS expected if you are initializing LLaMAModel from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).
- This IS NOT expected if you are initializing LLaMAModel from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).```
<|||||>`LLaMAModel` excludes the LM Head. You want to use `LLaMAForCausalLM` instead.<|||||><img width="977" alt="image" src="https://user-images.githubusercontent.com/106687776/223898571-7866feb7-ba02-4641-be86-c424aef03883.png">

@zphang  getting the following err. any clue?<|||||>> `LLaMAModel` excludes the LM Head. You want to use `LLaMAForCausalLM` instead.

So the error is expected when calling this class? I see other models are silencing it with `_keys_to_ignore_on_load_unexpected = [r"decoder\.version", r"lm_head.weight"]` in XXXPreTrainedModel.

I know why I'm calling this class directly, I was just uneasy that I got this error with LLaMA and not with other models (e.g. Bloom), but later I found this difference in `_keys_to_ignore_on_load_unexpected `<|||||>I don't think I see that in OPT or GPT-NeoX-20B.<|||||>Can the code be used for finetuning? I tried simply to finetune llama-33b using deepspeed on 8x40gA100, but it seems batch-size can only be 1, while in the same ds config and GPU environment, I can finetune opt-iml-33b with batch_size 8. I wonder if it is the code that can not be well used for finetuning using deepspeed?<|||||>> <img alt="image" width="977" src="https://user-images.githubusercontent.com/106687776/223898571-7866feb7-ba02-4641-be86-c424aef03883.png">
> 
> @zphang getting the following err. any clue?

Try installing llama requirements packages (Before that, make sure you installed zphang's llama_push repo)
`git clone https://github.com/facebookresearch/llama`
`pip install -r requirements.txt`<|||||>> Can the code be used for finetuning? I tried simply to finetune llama-33b using deepspeed on 8x40gA100, but it seems batch-size can only be 1, while in the same ds config and GPU environment, I can finetune opt-iml-33b with batch_size 8. I wonder if it is the code that can not be well used for finetuning using deepspeed?

I have the same problem, on 4*A100 40G, for BLOOMZ 7B can be 8 batch, llama 7B can only be 1batch.<|||||>I get different results in the original PR implementation (which had licensing issues) and the current, modified implementation. 

Using the prompt `This is a story about` and

```
output = model.generate(input_ids, do_sample=False)

```
 I get these outputs:

## Original:

> This is a story about how we got here, and the challenges ahead.
The first time I saw a drone was in 2013 when my wife and I were visiting our daughter at college. We went to her dorm room one afternoon to drop off some things she needed for class that day, and as soon as we walked into the lobby, there it was: a quadcopter hovering just above us, its four propellers spinning lazily in the air. It wasn’t doing anything special—it was just flying around on its own, like an insect buzzing around your head. But it made me feel uneasy; I didn’t know what to make of this new technology. The next year, after I had moved back home from Washington, D.C., where I worked for a nonprofit, I started noticing them more often while walking through neighborhoods or hiking in the woods. Sometimes they would be parked

## Current:

> This is a story about a man who was born in the 1920s and lived through the Great Depression, World War II, and the Korean War. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He

Maybe I am doing something wrong, so can someone double check this?<|||||>We are noticing that unlike other models this model / tokenizer isn't adding spaces at the beginning of the generation.
Our interface is designed for continuous generation so if a user submits "Programmers are busy debugging the code" we would expect the generation " of the model generation." resulting in "Programmers are busy debugging the code of the model generation."

Instead we are seeing "of the model generation." resulting in "Programmers are busy debugging the codeof the model generation".

Is this to be expected on the latest version of the PR and conversion?<|||||>> We are noticing that unlike other models this model / tokenizer isn't adding spaces at the beginning of the generation. Our interface is designed for continuous generation so if a user submits "Programmers are busy debugging the code" we would expect the generation " of the model generation." resulting in "Programmers are busy debugging the code of the model generation."
> 
> Instead we are seeing "of the model generation." resulting in "Programmers are busy debugging the codeof the model generation".
> 
> Is this to be expected on the latest version of the PR and conversion?

This is expected based on the tokenizer provided by Facebook. The eos and bos tokens are literally empty strings. Perhaps for HuggingFace purposes this should be... reconsidered?<|||||>> I get different results in the original PR implementation (which had licensing issues) and the current, modified implementation.
> 
> Using the prompt `This is a story about` and
> 
> ```
> output = model.generate(input_ids, do_sample=False)
> ```
> 
> I get these outputs:
> ## Original:
> 
> > This is a story about how we got here, and the challenges ahead.
> > The first time I saw a drone was in 2013 when my wife and I were visiting our daughter at college. We went to her dorm room one afternoon to drop off some things she needed for class that day, and as soon as we walked into the lobby, there it was: a quadcopter hovering just above us, its four propellers spinning lazily in the air. It wasn’t doing anything special—it was just flying around on its own, like an insect buzzing around your head. But it made me feel uneasy; I didn’t know what to make of this new technology. The next year, after I had moved back home from Washington, D.C., where I worked for a nonprofit, I started noticing them more often while walking through neighborhoods or hiking in the woods. Sometimes they would be parked
> 
> ## Current:
> 
> > This is a story about a man who was born in the 1920s and lived through the Great Depression, World War II, and the Korean War. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He
> 
> Maybe I am doing something wrong, so can someone double check this?

@oobabooga 

What settings are you using to generate the text? I noticed I had to increase my repetition penalty, otherwise I'd see similar results as you. I'm currently getting pretty good results with these settings:

```
temp 0.8
rep_pen 1.18
top_k 67
top_p 0
do_sample false
```<|||||>Ok, I have looked more carefully and the biggest difference is that the original implementation didn't add an `bos_token` to the prompt and the current one does.

Trying again but removing the `bos_token` from the current version I get these outputs for the prompt `My name is`

## Original

> My name is Kyle and I am a 20 year old college student. I am a very outgoing person and I love to meet new people. I am very easy to get along with and I am very open minded. I am a very active person and I love to be outdoors. I love to go hiking, camping, and fishing. I am a very easy going person and I love to have fun. I am very respectful and I am very easy to

## Current

> My name is Kyle and I am a 20 year old college student. I am a very outgoing person and I love to meet new people. I am very easy to get along with and I am very open minded. I am a very active person and I love to be outdoors. I love to go hiking, camping, and fishing. I am a very athletic person and I love to play sports. I am a very competitive person and I love to

There is still a difference, but this time it's subtle. This is how I am testing the original implementation:

``` python
import gc
import importlib
from pathlib import Path
import torch
import os
import subprocess

def install(name):
    subprocess.call(['pip', 'uninstall', '-y', 'transformers'])
    subprocess.call(['pip', 'install', name])

install('git+https://github.com/oobabooga/transformers@llama_push')
import transformers

model = transformers.AutoModelForCausalLM.from_pretrained(Path(f"models/llama-7b-original"), torch_dtype=torch.float16).cuda()
tokenizer = transformers.AutoTokenizer.from_pretrained(Path(f"models/llama-7b-original"))

input_ids = tokenizer.encode("My name is", return_tensors='pt').cuda()
print(input_ids)
output = model.generate(input_ids, do_sample=False, max_new_tokens=100)[0]
print(tokenizer.decode(output, skip_special_tokens=True))

```

And the current:

``` python
import gc
import importlib
from pathlib import Path
import torch
import os
import subprocess

def install(name):
    subprocess.call(['pip', 'uninstall', '-y', 'transformers'])
    subprocess.call(['pip', 'install', name])

install('git+https://github.com/zphang/transformers@llama_push')
import transformers

model = transformers.AutoModelForCausalLM.from_pretrained(Path(f"models/llama-7b-current"), torch_dtype=torch.float16).cuda()
tokenizer = transformers.AutoTokenizer.from_pretrained(Path(f"models/llama-7b-current"))

input_ids = tokenizer.encode("My name is", return_tensors='pt').cuda()
input_ids = input_ids[:,1:]
print(input_ids)
output = model.generate(input_ids, do_sample=False, max_new_tokens=100)[0]
print(tokenizer.decode(output, skip_special_tokens=True))

```

@rohvani the point is to use deterministic sampling to make sure that the two implementations yield the exact same results.<|||||>> Ok, I have looked more carefully and the biggest difference is that the original implementation didn't add an `bos_token` to the prompt and the current one does.
> 
> Trying again but removing the `bos_token` from the current version I get these outputs for the prompt `My name is`
> 
> ## Original
> > My name is Kyle and I am a 20 year old college student. I am a very outgoing person and I love to meet new people. I am very easy to get along with and I am very open minded. I am a very active person and I love to be outdoors. I love to go hiking, camping, and fishing. I am a very easy going person and I love to have fun. I am very respectful and I am very easy to
> 
> ## Current
> > My name is Kyle and I am a 20 year old college student. I am a very outgoing person and I love to meet new people. I am very easy to get along with and I am very open minded. I am a very active person and I love to be outdoors. I love to go hiking, camping, and fishing. I am a very athletic person and I love to play sports. I am a very competitive person and I love to
> 
> There is still a difference, but this time it's subtle. This is how I am testing the original implementation:
> 
> ```python
> import gc
> import importlib
> from pathlib import Path
> import torch
> import os
> import subprocess
> 
> def install(name):
>     subprocess.call(['pip', 'uninstall', '-y', 'transformers'])
>     subprocess.call(['pip', 'install', name])
> 
> install('git+https://github.com/oobabooga/transformers@llama_push')
> import transformers
> 
> model = transformers.AutoModelForCausalLM.from_pretrained(Path(f"models/llama-7b-original"), torch_dtype=torch.float16).cuda()
> tokenizer = transformers.AutoTokenizer.from_pretrained(Path(f"models/llama-7b-original"))
> 
> input_ids = tokenizer.encode("My name is", return_tensors='pt').cuda()
> print(input_ids)
> output = model.generate(input_ids, do_sample=False, max_new_tokens=100)[0]
> print(tokenizer.decode(output, skip_special_tokens=True))
> ```
> 
> And the current:
> 
> ```python
> import gc
> import importlib
> from pathlib import Path
> import torch
> import os
> import subprocess
> 
> def install(name):
>     subprocess.call(['pip', 'uninstall', '-y', 'transformers'])
>     subprocess.call(['pip', 'install', name])
> 
> install('git+https://github.com/zphang/transformers@llama_push')
> import transformers
> 
> model = transformers.AutoModelForCausalLM.from_pretrained(Path(f"models/llama-7b-current"), torch_dtype=torch.float16).cuda()
> tokenizer = transformers.AutoTokenizer.from_pretrained(Path(f"models/llama-7b-current"))
> 
> input_ids = tokenizer.encode("My name is", return_tensors='pt').cuda()
> input_ids = input_ids[:,1:]
> print(input_ids)
> output = model.generate(input_ids, do_sample=False, max_new_tokens=100)[0]
> print(tokenizer.decode(output, skip_special_tokens=True))
> ```
> 
> @rohvani the point is to use deterministic sampling to make sure that the two implementations yield the exact same results.

We dont want the same results, as the previous implementation was flawed.<|||||>LGTM then.<|||||>Regarding the above comments: yes, it is important to separate the tokenizer behavior and model behavior.

On the tokenizer: I think you should not rely on the default appending/prepending of EOS/BOS, especially when testing across different models. Different model families have different special token behavior in different cases (e.g. I believe for most cases in generation, you do not want EOS appended, even though this is the default in some models). It would be better to provide add_eos_token / add_bos_token explicitly in your usage.

On the model: Yes, I believe there may still be some subtle differences between the actual model implementation between the old and refactored version. Off the top of my head, the RoPE embeddings and RMSNorms have totally different implementations: they should be mathematically identical, but may be numerically different. I will continue to look into this, but providing more reproducible examples of differences would be extremely helpful.

Thanks all for the feedback! It has been very helpful in helping me track down issues with my implementation.<|||||>To come back on the BOS token point, I actually am not certain that is the issue. In models that behave correctly it is the choice of the model to add the space. But it is not guaranteed behavior. For example on a correct model something like "I like to play foot" might generate "ball with my friends" resulting in "I like to play football with my friends" but these models still have the ability to detect when a space should be used. That means that on the existing models this behavior is not hardcoded.

In the earlier mentioned examples the behavior persists on this LLaMA implementation when it does not make sense and there clearly should have been a space. It also means workarounds for the issue are unreliable because if you wish to continue a partial generation it would be undesirable for us to forcefully inject spaces while the AI may have been trying to use one of those combined words like football when it got cut off. <|||||>> We are noticing that unlike other models this model / tokenizer isn't adding spaces at the beginning of the generation. Our interface is designed for continuous generation so if a user submits "Programmers are busy debugging the code" we would expect the generation " of the model generation." resulting in "Programmers are busy debugging the code of the model generation."
> 
> Instead we are seeing "of the model generation." resulting in "Programmers are busy debugging the codeof the model generation".
> 
> Is this to be expected on the latest version of the PR and conversion?

This is a SentencePiece behavior rather than something model specific - it always trims space/linefeed(s) at the beginning of output. Unless I am mistaken, SPM itself must be modified to fix this behavior.<|||||>@zphang very interested in this new feature, do you guys have any timeline of merging it into master?<|||||>> It also means workarounds for the issue are unreliable because if you wish to continue a partial generation it would be undesirable for us to forcefully inject spaces while the AI may have been trying to use one of those combined words like football when it got cut off.

Hi, just tested this, and I understand what you mean. This is an issue with the tokenizer decoding rather than encoding. As @syskn mentioned, this is an issue with the sentencepiece, not the implementation (e.g. the T5 tokenizer, which also uses SPM, has the same issue). Given that this behavior also exists in T5, a widely used model, I don't think the HF folks are likely to want to have this depart from the expected behavior then. I think this may be something you need to address downstream on your end.

One simple (if manual) fix may be the following:

```python
vocab = tokenizer.convert_ids_to_tokens(range(tokenizer.vocab_size))
NO_SPACE_SET = {
    i
    for i, tok in enumerate(vocab)
    if not tok.startswith("▁")
}

def llama_decode(model_output):
    decoded = tokenizer.decode(model_output)
    if model_output and model_output[0] not in NO_SPACE_SET:
        decoded = " " + decoded
    return decoded

# Prepends space
print(f"'{llama_decode([7199, 1612, 825])}'")
# doesn't prepend space
print(f"'{llama_decode([53, 19, 1633])}'")
```

(Basically tokenizers are weird and difficult.)<|||||>@zpang that is unfortunate because that means that the way sentencepiece is handled isn't suitable for the real world use cases of models that complete text. I will then indeed have to do the always add a space workaround which can hinder the experience.

T5 is an entirely different model not suitable for our use case. A model like LLaMA has a real world use case of completing text in a text editor in a seamless experience rather than an input and an output field. While this behavior isn't bad or even desirable in a seperate output field it can really hinder continuous generation if everything is unified in a single editor.

For now ill resort to implementing a workaround like you suggested, but it is good for the wider AI community to knows this kind of behavior on a model intended to complete text hurts real world performance. It would be much better if the model were able to pick a space as a token rather than me having to pick between no spaces or always spaces.<|||||>>T5 is an entirely different model not suitable for our use case. A model like LLaMA has a real world use case of completing text in a text editor in a seamless experience rather than an input and an output field.

I understand where you're coming from, but I'm just trying to provide the context of broader language models. Many language models (in the modern usage of the term) aren't centered on generation. This includes broad classes of models like BERT and T5 that aren't used in GPT-like ways.

And on your second note: I'm not sure if this is a fundamental limitation of sentencepiece, or just the chosen implementation (on the SPM side) for decoding tokens. As described above, the information to decode correctly with the space is there, it's just that the decode method doesn't support it. Thinking about it more, I think we could add an option to the tokenizer implementation to enable this behavior -- this would not be that out of place given the existence of other previous hacks like "add prefix space". (Thinking about it even more, maybe this *should* be the default behavior.)

Also, to answer more questions about merging, the HF folks have asked me to ping them when I think this is good to merge. I plan to spend some time looking through the issues raised above this weekend, and pinging them on Monday, and I think I can raise this as an issue as well.<|||||>@zphang  I'm not sure what has changed in the your branch. But I'm getting this error 

```ValueError: Tokenizer class LLaMATokenizer does not exist or is not currently imported.```

While trying this code

```
import gc
import importlib
from pathlib import Path
import torch
import os
import subprocess

def install(name):
    subprocess.call(['pip', 'uninstall', '-y', 'transformers'])
    subprocess.call(['pip', 'install', name])

install('git+https://github.com/zphang/transformers@llama_push')
import transformers

model = transformers.AutoModelForCausalLM.from_pretrained(Path(f"models/llama-7b-current"), torch_dtype=torch.float16).cuda()
tokenizer = transformers.AutoTokenizer.from_pretrained(Path(f"models/llama-7b-current"))

input_ids = tokenizer.encode("My name is", return_tensors='pt').cuda()
input_ids = input_ids[:,1:]
print(input_ids)
output = model.generate(input_ids, do_sample=False, max_new_tokens=100)[0]
print(tokenizer.decode(output, skip_special_tokens=True))
```
<|||||>On the other hand, If I try with the original implementation (with which this PR was started), i'm getting completely gibberish, This is the output for the input prompt `My name is`

```
My name isanto Dresclockulaireɒ повеisterug Clarkjuierslexvir polcibleteiyenibtzewINF CommissionFEzat Metropolasi summ Package Stadiumiarogleorf EnciqueowieщенędzISO mand Fichieravantskystag _ILvueutilsверropSERTгро PitaudiatzATCH midortenscheid Tableisoreicheanguage riencloudflare!("meisterINTlauychcykhausenrameramePlotнат Kontrola LauritoundialذativvorñaccalachJB shootfaretr Epetuenig százonCreate chamber dob▲ascibilcinaglia
``` 

I was using this model hosted on HF 

"decapoda-research/llama-7b-hf"<|||||>@zphang  Hi, I got some error with follow code:
```python
import transformers
import torch

device = "cuda:0" if torch.cuda.is_available() else "cpu"

tokenizer = transformers.LLaMATokenizer.from_pretrained("LLaMA-hf/llama-7b")
model = transformers.LLaMAForCausalLM.from_pretrained("LLaMA-hf/llama-7b").to(device)

batch = tokenizer(
    "The primary use of LLaMA is research on large language models, including",
    return_tensors="pt", 
    add_special_tokens=False
)
batch = {k: v.cuda() for k, v in batch.items()}
generated = model.generate(batch["input_ids"], max_length=100)
print(tokenizer.decode(generated[0]))
```
Error:
```bash
File ./venv/lib/python3.8/site-packages/transformers/models/llama/modeling_llama.py:228, in LLaMAAttention.forward(self, hidden_states, past_key_value, attention_mask, output_attentions)
    226     kv_seq_len += offset
    227 cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
--> 228 query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, offset=offset)
    229 # [bsz, nh, t, hd]
    231 if past_key_value is not None:
    232     # reuse k, v, self_attention

File ./venv/lib/python3.8/site-packages/transformers/models/llama/modeling_llama.py:142, in apply_rotary_pos_emb(q, k, cos, sin, offset)
    140 cos = cos[..., offset : q.shape[-2] + offset, :]
    141 sin = sin[..., offset : q.shape[-2] + offset, :]
--> 142 q_embed = (q * cos) + (rotate_half(q) * sin)
    143 k_embed = (k * cos) + (rotate_half(k) * sin)
    144 return q_embed, k_embed

File ./venv/lib/python3.8/site-packages/transformers/models/llama/modeling_llama.py:136, in rotate_half(x)
    134 x1 = x[..., : x.shape[-1] // 2]
    135 x2 = x[..., x.shape[-1] // 2]
--> 136 return torch.cat((-x2, x1), dim=-1)

RuntimeError: Tensors must have same number of dimensions: got 3 and 4
```
transformers version: [a3dfcc02d249cbd14ce9089f57d4040146f3f090](https://github.com/zphang/transformers/commit/a3dfcc02d249cbd14ce9089f57d4040146f3f090)
<|||||>@mymusise where did you get these models from?<|||||>> @mymusise where did you get these models from?

@amrrs  Did you mean the transformers implementation of llama?
Here, the latest code of this PR: https://github.com/zphang/transformers/tree/llama_push
<|||||>> @zphang Hi, I got some error with follow code:
> 
> ```python
> import transformers
> import torch
> 
> device = "cuda:0" if torch.cuda.is_available() else "cpu"
> 
> tokenizer = transformers.LLaMATokenizer.from_pretrained("LLaMA-hf/llama-7b")
> model = transformers.LLaMAForCausalLM.from_pretrained("LLaMA-hf/llama-7b").to(device)
> 
> batch = tokenizer(
>     "The primary use of LLaMA is research on large language models, including",
>     return_tensors="pt", 
>     add_special_tokens=False
> )
> batch = {k: v.cuda() for k, v in batch.items()}
> generated = model.generate(batch["input_ids"], max_length=100)
> print(tokenizer.decode(generated[0]))
> ```
> 
> Error:
> 
> ```shell
> File ./venv/lib/python3.8/site-packages/transformers/models/llama/modeling_llama.py:228, in LLaMAAttention.forward(self, hidden_states, past_key_value, attention_mask, output_attentions)
>     226     kv_seq_len += offset
>     227 cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
> --> 228 query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, offset=offset)
>     229 # [bsz, nh, t, hd]
>     231 if past_key_value is not None:
>     232     # reuse k, v, self_attention
> 
> File ./venv/lib/python3.8/site-packages/transformers/models/llama/modeling_llama.py:142, in apply_rotary_pos_emb(q, k, cos, sin, offset)
>     140 cos = cos[..., offset : q.shape[-2] + offset, :]
>     141 sin = sin[..., offset : q.shape[-2] + offset, :]
> --> 142 q_embed = (q * cos) + (rotate_half(q) * sin)
>     143 k_embed = (k * cos) + (rotate_half(k) * sin)
>     144 return q_embed, k_embed
> 
> File ./venv/lib/python3.8/site-packages/transformers/models/llama/modeling_llama.py:136, in rotate_half(x)
>     134 x1 = x[..., : x.shape[-1] // 2]
>     135 x2 = x[..., x.shape[-1] // 2]
> --> 136 return torch.cat((-x2, x1), dim=-1)
> 
> RuntimeError: Tensors must have same number of dimensions: got 3 and 4
> ```
> 
> transformers version: [a3dfcc02d249cbd14ce9089f57d4040146f3f090](https://github.com/zphang/transformers/commit/a3dfcc02d249cbd14ce9089f57d4040146f3f090)

@zphang  Hi, here's a PR for fix this: https://github.com/zphang/transformers/pull/3/files

Looks like this was little accidentally changed in this commit: https://github.com/zphang/transformers/commit/e2faccb96ae76460408f559bdde51dc6dda28847#diff-06392bad3b9e97be9ade60d4ac46f73b6809388f4d507c2ba1384ab872711c51L135
<|||||>There is some difference between the implementation of rotary position embedding in [PR
](https://github.com/zphang/transformers/blob/a3dfcc02d249cbd14ce9089f57d4040146f3f090/src/transformers/models/llama/modeling_llama.py#L100)  and [llama inference](https://github.com/facebookresearch/llama/blob/57b0eb62de0636e75af471e49e2f1862d908d9d8/llama/model.py#L47)

maybe the problem is in  [this line](https://github.com/zphang/transformers/blob/a3dfcc02d249cbd14ce9089f57d4040146f3f090/src/transformers/models/llama/modeling_llama.py#L135)
change the following into
`x2 = x[..., :x.shape[-1] // 2]`<|||||>> 

You can try to install sentencepiece

```
pip install sentencepiece
```<|||||>Thanks all, corrected two mistakes from my commit last night. Hopefully this version is close to final.<|||||>Inference with this code requires significantly more memory than with Facebook's impl. Not sure if I'm doing something wrong or if it's a real problem.

- Facebook impl: 30B model (re-sharded for world size 2) fits in ~68GB VRAM and can do 1024 sequence length no problem. ~16 tokens per second.
- This impl: 30B model exceeds 96GB VRAM and puts additional 20ish GB on CPU. Fails for 1024 sequence length; can do 128 but very slow. Quantizing brings it down to 34GB but still slower than Facebook.<|||||>@haydenshively What code are you using on the Transformers side? Are you sure you are sending `torch_dtype=torch.float16` or `torch_dtype=torch.bfloat16` as it looks like you have a model in FP32 with all the memory used.<|||||>Giving a heads up: the HF folks have requested I rename some of the class names to follow full camel-case (e.g. `LlamaModel` rather than `LLaMAModel`, so expect that to kick in in an upcoming commit.<|||||>@zphang I saw the tokenizer config changed to where the BOS token is a space, is the proper behavior where the model decides the usage still planned? For example the test sentence "My favorite sport is foot" produces "My favorite sport is foot bal".
While I agree that always spaces is better than never spaces (It would have been my workaround to), i'd rather see the earlier mentioned tokenizer change to where the tokenizer no longer trims the first space if the model decides to do it.

Or did it turn out the model can't do that after all?<|||||>I added a `decode_with_prefix_space` option (though currently still defaults to False). I've also asked the HF folks to chime in on this issue (they should be reviewing it tomorrow), so the current functionality isn't quite finalized yet.

(`decode_with_prefix_space` only adds a space if the first token requires a prefix space.)<|||||>> I added a `decode_with_prefix_space` option (though currently still defaults to False). I've also asked the HF folks to chime in on this issue (they should be reviewing it tomorrow), so the current functionality isn't quite finalized yet.
> 
> (`decode_with_prefix_space` only adds a space if the first token requires a prefix space.)

Am I correct in seeing that the BOS token is now a space? Would this cause issues if I enable that option to where we then get double spaces or does it change the bos behavior? Because on the latest conversions I am noticing the spaces are being added, but also in the cases where they shouldn't be.

Our software uses AutoModelForCausalLM by default, I assume to apply decode_with_prefix_space I have to load it more direct?

Update: Seems like I can answer my own question. I'd need to manually call the LLaMATokenizer with the add_bos_token=False, decode_with_prefix_space=True options. This should then eliminate the always adding a space behavior, and restores the behavior I seek.

Personally I would vote that to be the defaults since to me adding a space as the BOS at all times is undesirable behavior compared to the decode_with_prefix_space solution. And I can imagine other projects who do not want decode_with_prefix_space would not want the space as the bos token either.<|||||>> I'd need to manually call the LLaMATokenizer with the add_bos_token=False, decode_with_prefix_space=True options.

Yes. Alternatively, set those attributes after instantiating (I presume from an AutoTokenizer). 

I don't really have a strong preference for what the default should be, but I suspect the HF folks might because these models feed into other HF infrastructure (e.g. pipelines) which may influence what they want for the default. I think that as long as the implementation supports the different use-cases, and the user can choose what behavior they want, that would be best for all.<|||||>Understood, for downstream projects the suggested behavior most closely resembles what the AutoModelForCausalLM models combined with AutoTokenizer do for the other implementations. So I hope that is the behavior that HF will conclude, otherwise it will be the beginning of us needing to do model specific tokenizer calls rather than relying on AutoTokenizer's defaults.<|||||>I also started to run into `ValueError: Tokenizer class LLaMATokenizer does not exist or is not currently imported.` just as in https://github.com/huggingface/transformers/pull/21955#issuecomment-1465291081<|||||>What tokenizer settings should I use now to *not* having an extra space on the beginning? Adding extra space on the beginning suddenly started to break my code.<|||||>> @haydenshively What code are you using on the Transformers side? Are you sure you are sending `torch_dtype=torch.float16` or `torch_dtype=torch.bfloat16` as it looks like you have a model in FP32 with all the memory used.

It seems `torch_dtype` is set in class `PretrainedConfig` initialization, but bfloat16 is not set.<|||||>> I also started to run into `ValueError: Tokenizer class LLaMATokenizer does not exist or is not currently imported.` just as in [#21955 (comment)](https://github.com/huggingface/transformers/pull/21955#issuecomment-1465291081)

Ah, yes if sentencepiece is not available, the tokenizer import will magically fail at runtime:

<img width="464" alt="image" src="https://user-images.githubusercontent.com/1486609/224893072-1b6940b5-f2a8-42d8-a51c-637cd1fe6507.png">
<|||||>I've been doing some testing with this model. In particular, I made the following dummy function that utilizes the model's forward method:

```
def gen_next_tokens(inp, model, max_gen_len, mask_id):
    tokenized = tokenizer.encode(inp, return_tensors='pt').to(DEV)
    total_len = min(model.seqlen, max_gen_len + tokenized.shape[1])

    tokens = torch.full((1, total_len), mask_id).to(DEV)
    tokens[0, :tokenized.shape[1]] = tokenized[0]
    attention_mask = tokens != mask_id
    past_key_values = None

    for cur_id in range(tokenized.shape[1], total_len):
        print(cur_id - tokenized.shape[1])
        if past_key_values:
            output = model(tokens, attention_mask, past_key_values=past_key_values, use_cache=True)
        else:
            output = model(tokens, attention_mask=attention_mask, use_cache=True)
        
        past_key_values = output.past_key_values
        logits = output.logits

        next_token = torch.argmax(logits, axis=-1)[0][cur_id-1]
        tokens[0, cur_id] = next_token
        attention_mask[0, cur_id] = True
```

When taking the past_key_values tuples I get and plugging them back into the model's forward function, I get the following error:

```
[/usr/local/lib/python3.9/dist-packages/transformers/models/llama/modeling_llama.py](https://localhost:8080/#) in _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length)
    490             )
    491             combined_attention_mask = (
--> 492                 expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
    493             )
    494 

RuntimeError: The size of tensor a (391) must match the size of tensor b (782) at non-singleton dimension 3
```

Is this expected behavior? Is there some form of preprocessing that needs to be done on past_key_values?<|||||>> I've been doing some testing with this model. In particular, I made the following dummy function that utilizes the model's forward method:
> 
> ```
> def gen_next_tokens(inp, model, max_gen_len, mask_id):
>     tokenized = tokenizer.encode(inp, return_tensors='pt').to(DEV)
>     total_len = min(model.seqlen, max_gen_len + tokenized.shape[1])
> 
>     tokens = torch.full((1, total_len), mask_id).to(DEV)
>     tokens[0, :tokenized.shape[1]] = tokenized[0]
>     attention_mask = tokens != mask_id
>     past_key_values = None
> 
>     for cur_id in range(tokenized.shape[1], total_len):
>         print(cur_id - tokenized.shape[1])
>         if past_key_values:
>             output = model(tokens, attention_mask, past_key_values=past_key_values, use_cache=True)
>         else:
>             output = model(tokens, attention_mask=attention_mask, use_cache=True)
>         
>         past_key_values = output.past_key_values
>         logits = output.logits
> 
>         next_token = torch.argmax(logits, axis=-1)[0][cur_id-1]
>         tokens[0, cur_id] = next_token
>         attention_mask[0, cur_id] = True
> ```
> 
> When taking the past_key_values tuples I get and plugging them back into the model's forward function, I get the following error:
> 
> ```
> [/usr/local/lib/python3.9/dist-packages/transformers/models/llama/modeling_llama.py](https://localhost:8080/#) in _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length)
>     490             )
>     491             combined_attention_mask = (
> --> 492                 expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
>     493             )
>     494 
> 
> RuntimeError: The size of tensor a (391) must match the size of tensor b (782) at non-singleton dimension 3
> ```
> 
> Is this expected behavior? Is there some form of preprocessing that needs to be done on past_key_values?

Firstly, you are not doing this right. When you pass `past_key_values` you are not supposed to be passing tokens for which you provide `past_key_values` (in your example you need to pass `next_token` as `input_ids` when using cache).
Secondly, [a fix](https://github.com/huggingface/transformers/pull/21955/commits/ef61b1ba1a8ee9fd354b640b059c3474b676c0c5) has just been pushed to finally fix LLaMA's `past_key_values`. Give it a try!<|||||>> > I've been doing some testing with this model. In particular, I made the following dummy function that utilizes the model's forward method:
> > ```
> > def gen_next_tokens(inp, model, max_gen_len, mask_id):
> >     tokenized = tokenizer.encode(inp, return_tensors='pt').to(DEV)
> >     total_len = min(model.seqlen, max_gen_len + tokenized.shape[1])
> > 
> >     tokens = torch.full((1, total_len), mask_id).to(DEV)
> >     tokens[0, :tokenized.shape[1]] = tokenized[0]
> >     attention_mask = tokens != mask_id
> >     past_key_values = None
> > 
> >     for cur_id in range(tokenized.shape[1], total_len):
> >         print(cur_id - tokenized.shape[1])
> >         if past_key_values:
> >             output = model(tokens, attention_mask, past_key_values=past_key_values, use_cache=True)
> >         else:
> >             output = model(tokens, attention_mask=attention_mask, use_cache=True)
> >         
> >         past_key_values = output.past_key_values
> >         logits = output.logits
> > 
> >         next_token = torch.argmax(logits, axis=-1)[0][cur_id-1]
> >         tokens[0, cur_id] = next_token
> >         attention_mask[0, cur_id] = True
> > ```
> > 
> > 
> >     
> >       
> >     
> > 
> >       
> >     
> > 
> >     
> >   
> > When taking the past_key_values tuples I get and plugging them back into the model's forward function, I get the following error:
> > ```
> > [/usr/local/lib/python3.9/dist-packages/transformers/models/llama/modeling_llama.py](https://localhost:8080/#) in _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length)
> >     490             )
> >     491             combined_attention_mask = (
> > --> 492                 expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
> >     493             )
> >     494 
> > 
> > RuntimeError: The size of tensor a (391) must match the size of tensor b (782) at non-singleton dimension 3
> > ```
> > 
> > 
> >     
> >       
> >     
> > 
> >       
> >     
> > 
> >     
> >   
> > Is this expected behavior? Is there some form of preprocessing that needs to be done on past_key_values?
> 
> Firstly, you are not doing this right. When you pass `past_key_values` you are not supposed to be passing tokens for which you provide `past_key_values` (in your example you need to pass `next_token` as `input_ids` when using cache). Secondly, [a fix](https://github.com/huggingface/transformers/pull/21955/commits/ef61b1ba1a8ee9fd354b640b059c3474b676c0c5) has just been pushed to finally fix LLaMA's `past_key_values`. Give it a try!

Excellent, I'll give that a shot. Thanks so much!

EDIT: Worked like a charm. Looks good to me.<|||||>I got the following error:

Some weights of the model checkpoint at /media/user/80EADB63EADB53CE/LLaMA/LLaMA_converted/llama-7b were not used when initializing LLaMAForCausalLM: ['model.decoder.layers.0.self_attn.v_proj.weight', 'model.decoder.layers.4.self_attn.k_proj.weight', 'model.decoder.layers.19.self_attn.k_proj.weight', 'model.decoder.layers.23.attention_norm.weight', 'model.decoder.layers.5.feed_forward.w3.weight', 'model.decoder.layers.14.self_attn.k_proj.weight', 'model.decoder.layers.26.feed_forward.w1.weight', 'model.decoder.layers.22.feed_forward.w3.weight', 'model.decoder.layers.12.attention_norm.weight', 'model.decoder.layers.3.self_attn.k_proj.weight', 'model.decoder.layers.1.feed_forward.w1.weight', 'model.decoder.layers.20.self_attn.q_proj.weight', 'model.decoder.layers.14.self_attn.o_proj.weight', 'model.decoder.layers.10.attention_norm.weight', 'model.decoder.layers.1.self_attn.q_proj.weight', 'model.decoder.layers.28.self_attn.v_proj.weight', 'model.decoder.layers.8.self_attn.q_proj.weight', 'model.decoder.layers.26.attention_norm.weight', 'model.decoder.layers.6.feed_forward.w2.weight', 'model.decoder.layers.8.feed_forward.w3.weight', 'model.decoder.layers.26.feed_forward.w3.weight', 'model.decoder.layers.10.feed_forward.w2.weight', 'model.decoder.layers.5.self_attn.q_proj.weight', 'model.decoder.layers.10.ffn_norm.weight', 'model.decoder.layers.15.attention_norm.weight', 'model.decoder.layers.0.attention_norm.weight', 'model.decoder.layers.26.self_attn.o_proj.weight', 'model.decoder.layers.1.self_attn.k_proj.weight', 'model.decoder.layers.24.feed_forward.w1.weight', 'model.decoder.layers.27.self_attn.k_proj.weight', 'model.decoder.layers.12.feed_forward.w1.weight', 'model.decoder.layers.6.self_attn.v_proj.weight', 'model.decoder.layers.2.self_attn.k_proj.weight', 'model.decoder.layers.10.self_attn.v_proj.weight', 'model.decoder.layers.9.self_attn.k_proj.weight', 'model.decoder.layers.31.ffn_norm.weight', 'model.decoder.layers.4.self_attn.o_proj.weight', 'model.decoder.layers.10.self_attn.k_proj.weight', 'model.decoder.layers.6.attention_norm.weight', 'model.decoder.layers.0.feed_forward.w1.weight', 'model.decoder.layers.11.self_attn.k_proj.weight', 'model.decoder.layers.14.attention_norm.weight', 'model.decoder.layers.18.feed_forward.w2.weight', 'model.decoder.layers.22.self_attn.k_proj.weight', 'model.decoder.layers.24.self_attn.o_proj.weight', 'model.decoder.layers.4.feed_forward.w2.weight', 'model.decoder.layers.23.self_attn.q_proj.weight', 'model.decoder.layers.25.feed_forward.w2.weight', 'model.decoder.layers.3.self_attn.v_proj.weight', 'model.decoder.layers.18.feed_forward.w1.weight', 'model.decoder.layers.30.self_attn.o_proj.weight', 'model.decoder.layers.7.ffn_norm.weight', 'model.decoder.layers.18.self_attn.q_proj.weight', 'model.decoder.layers.26.self_attn.k_proj.weight', 'model.decoder.layers.14.feed_forward.w1.weight', 'model.decoder.layers.27.self_attn.v_proj.weight', 'model.decoder.layers.14.feed_forward.w3.weight', 'model.decoder.layers.27.ffn_norm.weight', 'model.decoder.layers.14.self_attn.q_proj.weight', 'model.decoder.layers.25.ffn_norm.weight', 'model.decoder.layers.10.self_attn.q_proj.weight', 'model.decoder.layers.28.attention_norm.weight', 'model.decoder.layers.24.self_attn.q_proj.weight', 'model.decoder.layers.2.feed_forward.w1.weight', 'model.decoder.layers.2.self_attn.q_proj.weight', 'model.decoder.layers.0.self_attn.o_proj.weight', 'model.decoder.layers.18.ffn_norm.weight', 'model.decoder.layers.4.self_attn.q_proj.weight', 'model.decoder.layers.11.feed_forward.w3.weight', 'model.decoder.layers.25.self_attn.q_proj.weight', 'model.decoder.layers.25.self_attn.v_proj.weight', 'model.decoder.layers.21.self_attn.o_proj.weight', 'model.decoder.layers.3.ffn_norm.weight', 'model.decoder.layers.4.feed_forward.w3.weight', 'model.decoder.layers.16.feed_forward.w2.weight', 'model.decoder.layers.30.self_attn.v_proj.weight', 'model.decoder.layers.6.ffn_norm.weight', 'model.decoder.layers.12.self_attn.o_proj.weight', 'model.decoder.layers.12.feed_forward.w2.weight', 'model.decoder.layers.27.feed_forward.w1.weight', 'model.decoder.layers.29.feed_forward.w2.weight', 'model.decoder.layers.20.feed_forward.w3.weight', 'model.decoder.layers.24.attention_norm.weight', 'model.decoder.layers.29.self_attn.v_proj.weight', 'model.decoder.layers.23.self_attn.v_proj.weight', 'model.decoder.layers.19.attention_norm.weight', 'model.decoder.layers.26.self_attn.v_proj.weight', 'model.decoder.layers.14.ffn_norm.weight', 'model.decoder.layers.2.attention_norm.weight', 'model.decoder.layers.28.ffn_norm.weight', 'model.decoder.layers.12.ffn_norm.weight', 'model.decoder.layers.19.ffn_norm.weight', 'model.decoder.layers.30.feed_forward.w1.weight', 'model.decoder.layers.0.feed_forward.w2.weight', 'model.decoder.layers.21.ffn_norm.weight', 'model.decoder.layers.3.self_attn.q_proj.weight', 'model.decoder.layers.21.feed_forward.w1.weight', 'model.decoder.layers.27.feed_forward.w2.weight', 'model.decoder.layers.29.self_attn.k_proj.weight', 'model.decoder.layers.22.self_attn.o_proj.weight', 'model.decoder.layers.27.attention_norm.weight', 'model.decoder.layers.13.feed_forward.w3.weight', 'model.decoder.layers.8.self_attn.o_proj.weight', 'model.decoder.layers.14.feed_forward.w2.weight', 'model.decoder.layers.11.feed_forward.w1.weight', 'model.decoder.layers.15.self_attn.q_proj.weight', 'model.decoder.layers.5.self_attn.o_proj.weight', 'model.decoder.layers.12.self_attn.q_proj.weight', 'model.decoder.layers.12.self_attn.k_proj.weight', 'model.decoder.layers.18.self_attn.v_proj.weight', 'model.decoder.layers.22.feed_forward.w2.weight', 'model.decoder.layers.1.feed_forward.w3.weight', 'model.decoder.layers.20.attention_norm.weight', 'model.decoder.layers.3.attention_norm.weight', 'model.decoder.layers.24.self_attn.k_proj.weight', 'model.decoder.layers.7.feed_forward.w3.weight', 'model.decoder.layers.24.feed_forward.w2.weight', 'model.decoder.layers.25.feed_forward.w1.weight', 'model.decoder.norm.weight', 'model.decoder.layers.20.self_attn.o_proj.weight', 'model.decoder.layers.16.self_attn.k_proj.weight', 'model.decoder.layers.10.self_attn.o_proj.weight', 'model.decoder.layers.28.feed_forward.w2.weight', 'model.decoder.layers.29.attention_norm.weight', 'model.decoder.layers.17.self_attn.q_proj.weight', 'model.decoder.layers.19.feed_forward.w1.weight', 'model.decoder.layers.31.feed_forward.w2.weight', 'model.decoder.layers.7.self_attn.v_proj.weight', 'model.decoder.layers.21.attention_norm.weight', 'model.decoder.layers.19.feed_forward.w2.weight', 'model.decoder.layers.4.self_attn.v_proj.weight', 'model.decoder.layers.23.feed_forward.w3.weight', 'model.decoder.layers.9.feed_forward.w3.weight', 'model.decoder.layers.17.self_attn.o_proj.weight', 'model.decoder.layers.11.self_attn.v_proj.weight', 'model.decoder.layers.13.feed_forward.w2.weight', 'model.decoder.layers.17.feed_forward.w3.weight', 'model.decoder.layers.31.feed_forward.w3.weight', 'model.decoder.layers.13.self_attn.k_proj.weight', 'model.decoder.layers.9.feed_forward.w2.weight', 'model.decoder.layers.8.attention_norm.weight', 'model.decoder.layers.4.attention_norm.weight', 'model.decoder.layers.18.self_attn.k_proj.weight', 'model.decoder.layers.4.feed_forward.w1.weight', 'model.decoder.layers.2.feed_forward.w3.weight', 'model.decoder.layers.13.ffn_norm.weight', 'model.decoder.layers.19.feed_forward.w3.weight', 'model.decoder.layers.20.ffn_norm.weight', 'model.decoder.layers.18.self_attn.o_proj.weight', 'model.decoder.layers.28.self_attn.o_proj.weight', 'model.decoder.layers.7.self_attn.q_proj.weight', 'model.decoder.layers.7.self_attn.k_proj.weight', 'model.decoder.layers.0.self_attn.k_proj.weight', 'model.decoder.layers.9.feed_forward.w1.weight', 'model.decoder.layers.13.self_attn.q_proj.weight', 'model.decoder.layers.17.self_attn.v_proj.weight', 'model.decoder.layers.13.self_attn.o_proj.weight', 'model.decoder.layers.8.feed_forward.w1.weight', 'model.decoder.layers.0.feed_forward.w3.weight', 'model.decoder.layers.1.feed_forward.w2.weight', 'model.decoder.layers.3.self_attn.o_proj.weight', 'model.decoder.layers.16.self_attn.v_proj.weight', 'model.decoder.layers.7.self_attn.o_proj.weight', 'model.decoder.layers.11.self_attn.o_proj.weight', 'model.decoder.layers.15.feed_forward.w2.weight', 'model.decoder.layers.15.feed_forward.w1.weight', 'model.decoder.layers.28.self_attn.q_proj.weight', 'model.decoder.layers.8.ffn_norm.weight', 'model.decoder.layers.22.attention_norm.weight', 'model.decoder.layers.11.attention_norm.weight', 'model.decoder.layers.17.self_attn.k_proj.weight', 'model.decoder.layers.7.feed_forward.w2.weight', 'model.decoder.layers.27.feed_forward.w3.weight', 'model.decoder.layers.16.attention_norm.weight', 'model.decoder.layers.21.self_attn.v_proj.weight', 'model.decoder.layers.15.feed_forward.w3.weight', 'model.decoder.layers.20.self_attn.k_proj.weight', 'model.decoder.layers.15.self_attn.o_proj.weight', 'model.decoder.layers.31.self_attn.q_proj.weight', 'model.decoder.layers.2.self_attn.o_proj.weight', 'model.decoder.layers.29.feed_forward.w3.weight', 'model.decoder.layers.21.feed_forward.w2.weight', 'model.decoder.layers.23.self_attn.k_proj.weight', 'model.decoder.layers.5.self_attn.v_proj.weight', 'model.decoder.layers.5.ffn_norm.weight', 'model.decoder.layers.15.self_attn.v_proj.weight', 'model.decoder.layers.17.ffn_norm.weight', 'model.decoder.layers.8.feed_forward.w2.weight', 'model.decoder.layers.9.self_attn.v_proj.weight', 'model.decoder.layers.0.ffn_norm.weight', 'model.decoder.layers.20.self_attn.v_proj.weight', 'model.decoder.layers.23.self_attn.o_proj.weight', 'model.decoder.layers.29.ffn_norm.weight', 'model.decoder.layers.30.feed_forward.w2.weight', 'model.decoder.layers.11.ffn_norm.weight', 'model.decoder.layers.2.self_attn.v_proj.weight', 'model.decoder.layers.2.feed_forward.w2.weight', 'model.decoder.layers.3.feed_forward.w2.weight', 'model.decoder.layers.18.attention_norm.weight', 'model.decoder.layers.28.self_attn.k_proj.weight', 'model.decoder.embed_tokens.weight', 'model.decoder.layers.29.feed_forward.w1.weight', 'model.decoder.layers.30.ffn_norm.weight', 'model.decoder.layers.20.feed_forward.w2.weight', 'model.decoder.layers.12.self_attn.v_proj.weight', 'model.decoder.layers.20.feed_forward.w1.weight', 'model.decoder.layers.25.attention_norm.weight', 'model.decoder.layers.16.ffn_norm.weight', 'model.decoder.layers.25.feed_forward.w3.weight', 'model.decoder.layers.7.feed_forward.w1.weight', 'model.decoder.layers.8.self_attn.v_proj.weight', 'model.decoder.layers.6.feed_forward.w1.weight', 'model.decoder.layers.16.self_attn.q_proj.weight', 'model.decoder.layers.6.feed_forward.w3.weight', 'model.decoder.layers.21.feed_forward.w3.weight', 'model.decoder.layers.22.self_attn.q_proj.weight', 'model.decoder.layers.17.attention_norm.weight', 'model.decoder.layers.27.self_attn.q_proj.weight', 'model.decoder.layers.17.feed_forward.w1.weight', 'model.decoder.layers.11.feed_forward.w2.weight', 'model.decoder.layers.12.feed_forward.w3.weight', 'model.decoder.layers.13.self_attn.v_proj.weight', 'model.decoder.layers.28.feed_forward.w3.weight', 'model.decoder.layers.1.attention_norm.weight', 'model.decoder.layers.15.self_attn.k_proj.weight', 'model.decoder.layers.31.self_attn.k_proj.weight', 'model.decoder.layers.14.self_attn.v_proj.weight', 'model.decoder.layers.5.feed_forward.w2.weight', 'model.decoder.layers.19.self_attn.o_proj.weight', 'model.decoder.layers.31.self_attn.v_proj.weight', 'model.decoder.layers.22.ffn_norm.weight', 'model.decoder.layers.29.self_attn.q_proj.weight', 'model.decoder.layers.30.feed_forward.w3.weight', 'model.decoder.layers.5.self_attn.k_proj.weight', 'model.decoder.layers.7.attention_norm.weight', 'model.decoder.layers.29.self_attn.o_proj.weight', 'model.decoder.layers.31.self_attn.o_proj.weight', 'model.decoder.layers.16.feed_forward.w1.weight', 'model.decoder.layers.21.self_attn.q_proj.weight', 'model.decoder.layers.16.feed_forward.w3.weight', 'model.decoder.layers.1.ffn_norm.weight', 'model.decoder.layers.1.self_attn.v_proj.weight', 'model.decoder.layers.23.ffn_norm.weight', 'model.decoder.layers.30.attention_norm.weight', 'model.decoder.layers.22.self_attn.v_proj.weight', 'model.decoder.layers.5.feed_forward.w1.weight', 'model.decoder.layers.13.feed_forward.w1.weight', 'model.decoder.layers.3.feed_forward.w1.weight', 'model.decoder.layers.22.feed_forward.w1.weight', 'model.decoder.layers.10.feed_forward.w3.weight', 'model.decoder.layers.5.attention_norm.weight', 'model.decoder.layers.30.self_attn.k_proj.weight', 'model.decoder.layers.13.attention_norm.weight', 'model.decoder.layers.23.feed_forward.w1.weight', 'model.decoder.layers.17.feed_forward.w2.weight', 'model.decoder.layers.23.feed_forward.w2.weight', 'model.decoder.layers.9.self_attn.o_proj.weight', 'model.decoder.layers.24.self_attn.v_proj.weight', 'model.decoder.layers.26.feed_forward.w2.weight', 'model.decoder.layers.26.ffn_norm.weight', 'model.decoder.layers.9.attention_norm.weight', 'model.decoder.layers.28.feed_forward.w1.weight', 'model.decoder.layers.2.ffn_norm.weight', 'model.decoder.layers.19.self_attn.q_proj.weight', 'model.decoder.layers.24.feed_forward.w3.weight', 'model.decoder.layers.15.ffn_norm.weight', 'model.decoder.layers.26.self_attn.q_proj.weight', 'model.decoder.layers.11.self_attn.q_proj.weight', 'model.decoder.layers.9.ffn_norm.weight', 'model.decoder.layers.24.ffn_norm.weight', 'model.decoder.layers.31.attention_norm.weight', 'model.decoder.layers.10.feed_forward.w1.weight', 'model.decoder.layers.25.self_attn.o_proj.weight', 'model.decoder.layers.27.self_attn.o_proj.weight', 'model.decoder.layers.3.feed_forward.w3.weight', 'model.decoder.layers.6.self_attn.k_proj.weight', 'model.decoder.layers.4.ffn_norm.weight', 'model.decoder.layers.18.feed_forward.w3.weight', 'model.decoder.layers.19.self_attn.v_proj.weight', 'model.decoder.layers.30.self_attn.q_proj.weight', 'model.decoder.layers.31.feed_forward.w1.weight', 'model.decoder.layers.0.self_attn.q_proj.weight', 'model.decoder.layers.6.self_attn.o_proj.weight', 'model.decoder.layers.25.self_attn.k_proj.weight', 'model.decoder.layers.8.self_attn.k_proj.weight', 'model.decoder.layers.9.self_attn.q_proj.weight', 'model.decoder.layers.6.self_attn.q_proj.weight', 'model.decoder.layers.16.self_attn.o_proj.weight', 'model.decoder.layers.1.self_attn.o_proj.weight', 'model.decoder.layers.21.self_attn.k_proj.weight']
- This IS expected if you are initializing LLaMAForCausalLM from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).
- This IS NOT expected if you are initializing LLaMAForCausalLM from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).
Some weights of LLaMAForCausalLM were not initialized from the model checkpoint at /media/user/80EADB63EADB53CE/LLaMA/LLaMA_converted/llama-7b and are newly initialized: ['model.layers.13.self_attn.k_proj.weight', 'model.layers.22.mlp.gate_proj.weight', 'model.layers.1.self_attn.k_proj.weight', 'model.layers.2.post_attention_layernorm.weight', 'model.layers.10.self_attn.o_proj.weight', 'model.layers.5.self_attn.v_proj.weight', 'model.layers.28.self_attn.k_proj.weight', 'model.layers.17.self_attn.v_proj.weight', 'model.layers.26.self_attn.rotary_emb.inv_freq', 'model.layers.6.self_attn.q_proj.weight', 'model.layers.21.self_attn.k_proj.weight', 'model.layers.21.self_attn.v_proj.weight', 'model.layers.0.mlp.down_proj.weight', 'model.layers.29.mlp.down_proj.weight', 'model.layers.2.self_attn.o_proj.weight', 'model.layers.31.self_attn.k_proj.weight', 'model.layers.11.mlp.gate_proj.weight', 'model.layers.10.mlp.up_proj.weight', 'model.layers.29.post_attention_layernorm.weight', 'model.layers.4.input_layernorm.weight', 'model.layers.22.self_attn.o_proj.weight', 'model.layers.17.input_layernorm.weight', 'model.layers.5.self_attn.k_proj.weight', 'model.layers.26.self_attn.o_proj.weight', 'model.layers.6.post_attention_layernorm.weight', 'model.layers.8.self_attn.o_proj.weight', 'model.layers.9.self_attn.o_proj.weight', 'model.layers.28.mlp.gate_proj.weight', 'model.layers.7.self_attn.v_proj.weight', 'model.layers.11.mlp.up_proj.weight', 'model.layers.19.self_attn.k_proj.weight', 'model.layers.0.input_layernorm.weight', 'model.layers.14.self_attn.o_proj.weight', 'model.layers.15.self_attn.k_proj.weight', 'model.layers.25.self_attn.q_proj.weight', 'model.layers.28.mlp.down_proj.weight', 'model.layers.17.mlp.down_proj.weight', 'model.layers.25.input_layernorm.weight', 'model.layers.9.self_attn.v_proj.weight', 'model.layers.1.input_layernorm.weight', 'model.layers.19.self_attn.o_proj.weight', 'model.layers.9.mlp.gate_proj.weight', 'model.layers.26.mlp.down_proj.weight', 'model.layers.18.mlp.gate_proj.weight', 'model.layers.10.mlp.gate_proj.weight', 'model.layers.11.self_attn.v_proj.weight', 'model.layers.10.mlp.down_proj.weight', 'model.layers.16.input_layernorm.weight', 'model.layers.4.self_attn.q_proj.weight', 'model.layers.16.self_attn.rotary_emb.inv_freq', 'model.layers.27.mlp.down_proj.weight', 'model.layers.8.self_attn.rotary_emb.inv_freq', 'model.layers.1.mlp.gate_proj.weight', 'model.layers.8.self_attn.k_proj.weight', 'model.layers.27.post_attention_layernorm.weight', 'model.layers.6.mlp.gate_proj.weight', 'model.layers.6.self_attn.v_proj.weight', 'model.layers.25.self_attn.v_proj.weight', 'model.layers.30.mlp.up_proj.weight', 'model.layers.7.input_layernorm.weight', 'model.layers.28.self_attn.q_proj.weight', 'model.layers.6.self_attn.k_proj.weight', 'model.layers.27.self_attn.q_proj.weight', 'model.layers.28.post_attention_layernorm.weight', 'model.layers.21.self_attn.q_proj.weight', 'model.layers.25.post_attention_layernorm.weight', 'model.layers.5.post_attention_layernorm.weight', 'model.layers.13.self_attn.o_proj.weight', 'model.layers.14.post_attention_layernorm.weight', 'model.layers.18.post_attention_layernorm.weight', 'model.layers.6.input_layernorm.weight', 'model.layers.24.input_layernorm.weight', 'model.layers.3.self_attn.k_proj.weight', 'model.layers.2.mlp.up_proj.weight', 'model.layers.7.self_attn.rotary_emb.inv_freq', 'model.layers.31.self_attn.q_proj.weight', 'model.layers.15.mlp.up_proj.weight', 'model.layers.25.mlp.gate_proj.weight', 'model.layers.18.self_attn.q_proj.weight', 'model.layers.2.self_attn.q_proj.weight', 'model.layers.23.self_attn.rotary_emb.inv_freq', 'model.layers.0.self_attn.v_proj.weight', 'model.layers.19.post_attention_layernorm.weight', 'model.layers.19.mlp.gate_proj.weight', 'model.layers.1.self_attn.rotary_emb.inv_freq', 'model.layers.3.mlp.up_proj.weight', 'model.layers.17.mlp.up_proj.weight', 'model.layers.17.post_attention_layernorm.weight', 'model.layers.28.mlp.up_proj.weight', 'model.layers.24.self_attn.v_proj.weight', 'model.layers.7.post_attention_layernorm.weight', 'model.layers.1.self_attn.o_proj.weight', 'model.layers.18.mlp.up_proj.weight', 'model.layers.8.mlp.down_proj.weight', 'model.layers.26.mlp.gate_proj.weight', 'model.layers.6.mlp.down_proj.weight', 'model.layers.21.mlp.gate_proj.weight', 'model.layers.24.mlp.down_proj.weight', 'model.layers.16.post_attention_layernorm.weight', 'model.layers.1.mlp.down_proj.weight', 'model.layers.7.self_attn.o_proj.weight', 'model.layers.25.mlp.down_proj.weight', 'model.layers.10.self_attn.q_proj.weight', 'model.layers.30.self_attn.rotary_emb.inv_freq', 'model.layers.15.mlp.down_proj.weight', 'model.layers.1.self_attn.q_proj.weight', 'model.layers.19.input_layernorm.weight', 'model.layers.15.self_attn.v_proj.weight', 'model.layers.22.self_attn.v_proj.weight', 'model.layers.2.self_attn.v_proj.weight', 'model.layers.28.self_attn.rotary_emb.inv_freq', 'model.layers.28.input_layernorm.weight', 'model.layers.12.mlp.gate_proj.weight', 'model.layers.31.self_attn.rotary_emb.inv_freq', 'model.layers.7.self_attn.k_proj.weight', 'model.layers.8.mlp.gate_proj.weight', 'model.layers.24.self_attn.q_proj.weight', 'model.layers.27.input_layernorm.weight', 'model.layers.12.self_attn.k_proj.weight', 'model.layers.20.self_attn.o_proj.weight', 'model.layers.9.post_attention_layernorm.weight', 'model.layers.29.mlp.gate_proj.weight', 'model.layers.12.post_attention_layernorm.weight', 'model.layers.5.input_layernorm.weight', 'model.layers.20.mlp.down_proj.weight', 'model.layers.3.self_attn.v_proj.weight', 'model.layers.5.mlp.up_proj.weight', 'model.layers.8.self_attn.q_proj.weight', 'model.layers.12.self_attn.v_proj.weight', 'model.layers.18.input_layernorm.weight', 'model.layers.6.self_attn.o_proj.weight', 'model.layers.15.mlp.gate_proj.weight', 'model.layers.4.self_attn.v_proj.weight', 'model.layers.2.self_attn.rotary_emb.inv_freq', 'model.layers.27.self_attn.o_proj.weight', 'model.layers.10.self_attn.rotary_emb.inv_freq', 'model.layers.0.self_attn.o_proj.weight', 'model.layers.21.self_attn.o_proj.weight', 'model.layers.12.self_attn.o_proj.weight', 'model.layers.2.self_attn.k_proj.weight', 'model.layers.7.mlp.down_proj.weight', 'model.layers.30.mlp.down_proj.weight', 'model.layers.3.mlp.down_proj.weight', 'model.layers.4.post_attention_layernorm.weight', 'model.layers.29.self_attn.rotary_emb.inv_freq', 'model.layers.31.mlp.down_proj.weight', 'model.layers.29.self_attn.v_proj.weight', 'model.layers.17.mlp.gate_proj.weight', 'model.layers.26.input_layernorm.weight', 'model.layers.1.post_attention_layernorm.weight', 'model.layers.12.self_attn.rotary_emb.inv_freq', 'model.layers.4.mlp.gate_proj.weight', 'model.layers.1.self_attn.v_proj.weight', 'model.layers.0.self_attn.k_proj.weight', 'model.layers.24.self_attn.o_proj.weight', 'model.layers.29.self_attn.k_proj.weight', 'model.layers.5.self_attn.q_proj.weight', 'model.layers.9.mlp.up_proj.weight', 'model.layers.27.mlp.up_proj.weight', 'model.layers.15.post_attention_layernorm.weight', 'model.layers.6.mlp.up_proj.weight', 'model.layers.24.self_attn.rotary_emb.inv_freq', 'model.layers.14.mlp.up_proj.weight', 'model.layers.11.self_attn.q_proj.weight', 'model.layers.4.mlp.up_proj.weight', 'model.layers.20.self_attn.q_proj.weight', 'model.layers.25.mlp.up_proj.weight', 'model.layers.31.post_attention_layernorm.weight', 'model.layers.20.self_attn.rotary_emb.inv_freq', 'model.layers.17.self_attn.o_proj.weight', 'model.layers.15.self_attn.q_proj.weight', 'model.layers.22.post_attention_layernorm.weight', 'model.layers.9.self_attn.rotary_emb.inv_freq', 'model.embed_tokens.weight', 'model.layers.2.mlp.down_proj.weight', 'model.layers.15.self_attn.o_proj.weight', 'model.layers.27.self_attn.rotary_emb.inv_freq', 'model.layers.9.self_attn.k_proj.weight', 'model.layers.22.self_attn.q_proj.weight', 'model.layers.22.self_attn.rotary_emb.inv_freq', 'model.layers.14.self_attn.q_proj.weight', 'model.layers.22.input_layernorm.weight', 'model.layers.13.mlp.gate_proj.weight', 'model.layers.14.self_attn.v_proj.weight', 'model.layers.8.self_attn.v_proj.weight', 'model.layers.11.post_attention_layernorm.weight', 'model.layers.3.input_layernorm.weight', 'model.layers.13.self_attn.q_proj.weight', 'model.layers.15.self_attn.rotary_emb.inv_freq', 'model.layers.8.input_layernorm.weight', 'model.layers.11.self_attn.rotary_emb.inv_freq', 'model.layers.19.mlp.down_proj.weight', 'model.layers.18.mlp.down_proj.weight', 'model.layers.2.mlp.gate_proj.weight', 'model.layers.11.self_attn.o_proj.weight', 'model.layers.9.mlp.down_proj.weight', 'model.layers.20.mlp.gate_proj.weight', 'model.layers.23.mlp.gate_proj.weight', 'model.layers.16.self_attn.k_proj.weight', 'model.layers.26.self_attn.k_proj.weight', 'model.layers.1.mlp.up_proj.weight', 'model.layers.8.post_attention_layernorm.weight', 'model.layers.26.self_attn.q_proj.weight', 'model.layers.12.mlp.down_proj.weight', 'model.layers.23.self_attn.v_proj.weight', 'model.layers.3.self_attn.o_proj.weight', 'model.layers.9.self_attn.q_proj.weight', 'model.layers.14.mlp.gate_proj.weight', 'model.layers.16.self_attn.v_proj.weight', 'model.layers.17.self_attn.k_proj.weight', 'model.layers.23.self_attn.o_proj.weight', 'model.layers.13.mlp.up_proj.weight', 'model.layers.6.self_attn.rotary_emb.inv_freq', 'model.layers.13.self_attn.v_proj.weight', 'model.layers.25.self_attn.o_proj.weight', 'model.layers.0.mlp.gate_proj.weight', 'model.layers.30.input_layernorm.weight', 'model.layers.16.mlp.gate_proj.weight', 'model.layers.3.self_attn.rotary_emb.inv_freq', 'model.layers.2.input_layernorm.weight', 'model.layers.13.input_layernorm.weight', 'model.layers.14.self_attn.k_proj.weight', 'model.layers.19.self_attn.q_proj.weight', 'model.layers.30.self_attn.k_proj.weight', 'model.layers.3.self_attn.q_proj.weight', 'model.layers.18.self_attn.v_proj.weight', 'model.layers.31.self_attn.v_proj.weight', 'model.layers.11.self_attn.k_proj.weight', 'model.layers.30.mlp.gate_proj.weight', 'model.layers.20.self_attn.k_proj.weight', 'model.layers.20.mlp.up_proj.weight', 'model.layers.12.mlp.up_proj.weight', 'model.layers.15.input_layernorm.weight', 'model.layers.28.self_attn.v_proj.weight', 'model.layers.22.mlp.up_proj.weight', 'model.layers.18.self_attn.k_proj.weight', 'model.layers.7.mlp.gate_proj.weight', 'model.layers.30.self_attn.v_proj.weight', 'model.layers.20.input_layernorm.weight', 'model.layers.7.mlp.up_proj.weight', 'model.layers.10.post_attention_layernorm.weight', 'model.layers.13.post_attention_layernorm.weight', 'model.layers.16.self_attn.o_proj.weight', 'model.layers.23.self_attn.k_proj.weight', 'model.layers.0.self_attn.rotary_emb.inv_freq', 'model.layers.24.self_attn.k_proj.weight', 'model.layers.18.self_attn.o_proj.weight', 'model.layers.4.self_attn.k_proj.weight', 'model.layers.3.post_attention_layernorm.weight', 'model.layers.24.mlp.gate_proj.weight', 'model.layers.5.self_attn.o_proj.weight', 'model.layers.0.mlp.up_proj.weight', 'model.layers.11.input_layernorm.weight', 'model.layers.10.self_attn.k_proj.weight', 'model.layers.26.post_attention_layernorm.weight', 'model.layers.20.post_attention_layernorm.weight', 'model.layers.25.self_attn.k_proj.weight', 'model.layers.0.post_attention_layernorm.weight', 'model.layers.21.mlp.up_proj.weight', 'model.layers.10.self_attn.v_proj.weight', 'model.layers.24.post_attention_layernorm.weight', 'model.layers.19.self_attn.rotary_emb.inv_freq', 'model.layers.19.self_attn.v_proj.weight', 'model.layers.30.self_attn.o_proj.weight', 'model.layers.30.post_attention_layernorm.weight', 'model.layers.16.self_attn.q_proj.weight', 'model.layers.23.mlp.up_proj.weight', 'model.layers.26.self_attn.v_proj.weight', 'model.layers.19.mlp.up_proj.weight', 'model.layers.3.mlp.gate_proj.weight', 'model.layers.26.mlp.up_proj.weight', 'model.layers.29.self_attn.q_proj.weight', 'model.layers.9.input_layernorm.weight', 'model.layers.21.self_attn.rotary_emb.inv_freq', 'model.layers.0.self_attn.q_proj.weight', 'model.layers.11.mlp.down_proj.weight', 'model.layers.14.mlp.down_proj.weight', 'model.layers.31.input_layernorm.weight', 'model.layers.20.self_attn.v_proj.weight', 'model.layers.29.input_layernorm.weight', 'model.layers.13.mlp.down_proj.weight', 'model.layers.7.self_attn.q_proj.weight', 'model.layers.12.input_layernorm.weight', 'model.layers.21.mlp.down_proj.weight', 'model.layers.22.self_attn.k_proj.weight', 'model.layers.29.self_attn.o_proj.weight', 'model.layers.17.self_attn.rotary_emb.inv_freq', 'model.layers.21.input_layernorm.weight', 'model.layers.14.input_layernorm.weight', 'model.layers.31.mlp.gate_proj.weight', 'model.layers.14.self_attn.rotary_emb.inv_freq', 'model.layers.29.mlp.up_proj.weight', 'model.layers.30.self_attn.q_proj.weight', 'model.layers.23.mlp.down_proj.weight', 'model.layers.10.input_layernorm.weight', 'model.layers.22.mlp.down_proj.weight', 'model.layers.12.self_attn.q_proj.weight', 'model.layers.23.self_attn.q_proj.weight', 'model.layers.4.self_attn.o_proj.weight', 'model.layers.16.mlp.down_proj.weight', 'model.layers.23.input_layernorm.weight', 'model.layers.27.self_attn.k_proj.weight', 'model.layers.28.self_attn.o_proj.weight', 'model.layers.5.self_attn.rotary_emb.inv_freq', 'model.layers.5.mlp.gate_proj.weight', 'model.layers.21.post_attention_layernorm.weight', 'model.layers.8.mlp.up_proj.weight', 'model.layers.4.self_attn.rotary_emb.inv_freq', 'model.layers.17.self_attn.q_proj.weight', 'model.layers.24.mlp.up_proj.weight', 'model.layers.27.self_attn.v_proj.weight', 'model.layers.16.mlp.up_proj.weight', 'model.layers.18.self_attn.rotary_emb.inv_freq', 'model.layers.13.self_attn.rotary_emb.inv_freq', 'model.layers.5.mlp.down_proj.weight', 'model.layers.25.self_attn.rotary_emb.inv_freq', 'model.layers.27.mlp.gate_proj.weight', 'model.layers.31.self_attn.o_proj.weight', 'model.layers.31.mlp.up_proj.weight', 'model.layers.23.post_attention_layernorm.weight', 'model.norm.weight', 'model.layers.4.mlp.down_proj.weight']
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.<|||||>@ Everyone: I've pushed another breaking change to the code (renaming all LLaMA tokenizer, configuration and model classes to match the camelcase convention in HF Transformers (`LLaMA*` -> `Llama*`). This will require updating code, or at minimum, updating the configuration files for the tokenizers and models.

@sgugger I've incorporated all your feedback, except on updating the checkpointing script. I'm not sure if your comment meant that this can be updated in a PR; if not, I should be able to work on this tomorrow. Do let me know if anything else still needs addressing.<|||||>Hello, I have a question about training llama. Does the current version of training not support the zero strategy of deepspeed? I added the deepspeed configuration file, but it doesn't seem to take effect. Looking for your reply, thank you~<|||||>> I get different results in the original PR implementation (which had licensing issues) and the current, modified implementation.
> 
> Using the prompt `This is a story about` and
> 
> ```
> output = model.generate(input_ids, do_sample=False)
> ```
> 
> I get these outputs:
> 
> ## Original:
> > This is a story about how we got here, and the challenges ahead.
> > The first time I saw a drone was in 2013 when my wife and I were visiting our daughter at college. We went to her dorm room one afternoon to drop off some things she needed for class that day, and as soon as we walked into the lobby, there it was: a quadcopter hovering just above us, its four propellers spinning lazily in the air. It wasn’t doing anything special—it was just flying around on its own, like an insect buzzing around your head. But it made me feel uneasy; I didn’t know what to make of this new technology. The next year, after I had moved back home from Washington, D.C., where I worked for a nonprofit, I started noticing them more often while walking through neighborhoods or hiking in the woods. Sometimes they would be parked
> 
> ## Current:
> > This is a story about a man who was born in the 1920s and lived through the Great Depression, World War II, and the Korean War. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He
> 
> Maybe I am doing something wrong, so can someone double check this?

me too, there must be something wrong...
<|||||>> 
That may be caused by the different ways of rotary position embedding implementation.

I tried to check the output of rotary embeddings between this pr and raw llama infer code as follows,
```
### rotary implementation in raw code
import torch
class RotaryEmbedding(torch.nn.Module):
    def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
        super().__init__()
        inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
        self.register_buffer("inv_freq", inv_freq)

        # Build here to make `torch.jit.trace` work.
        self.max_seq_len_cached = max_position_embeddings
        t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
        freqs = torch.einsum("i,j->ij", t, self.inv_freq)
        # Different from paper, but it uses a different permutation in order to obtain the same calculation
        emb = torch.cat((freqs, freqs), dim=-1)
        self.cos_cached = emb.cos()[None, None, :, :]
        self.sin_cached = emb.sin()[None, None, :, :]

    def forward(self, x, seq_len=None):
        # x: [bs, num_attention_heads, seq_len, head_size]
        # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
        if seq_len > self.max_seq_len_cached:
            self.max_seq_len_cached = seq_len
            t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
            freqs = torch.einsum("i,j->ij", t, self.inv_freq)
            # Different from paper, but it uses a different permutation in order to obtain the same calculation
            emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
            self.cos_cached = emb.cos()[None, None, :, :].to(dtype=x.dtype)
            self.sin_cached = emb.sin()[None, None, :, :].to(dtype=x.dtype)
        return (
            self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype, device=x.device),
            self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype, device=x.device),
        )


def rotate_half(x):
    """Rotates half the hidden dims of the input."""
    x1 = x[..., : x.shape[-1] // 2]
    x2 = x[..., : x.shape[-1] // 2]
    print(x1.shape, x2.shape)
    return torch.cat((-x2, x1), dim=-1)


def apply_rotary_pos_emb(q, k, cos, sin, offset: int = 0):
    cos = cos[..., offset : q.shape[-2] + offset, :]
    sin = sin[..., offset : q.shape[-2] + offset, :]
    q_embed = (q * cos) + (rotate_half(q) * sin)
    k_embed = (k * cos) + (rotate_half(k) * sin)
    return q_embed, k_embed
q = torch.randn((2,32,2048,4096//32))
k = torch.randn((2,32,2048,4096//32))
v = torch.randn((2,32,2048,4096//32))
rotary_emb = RotaryEmbedding(4096//32)
cos, sin = rotary_emb(v, seq_len=2048)
q1, k1 = apply_rotary_pos_emb(q, k, cos, sin, offset=0)

### implementation in this repo
from typing import Tuple
def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0):
    freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
    t = torch.arange(end, device=freqs.device)  # type: ignore
    freqs = torch.outer(t, freqs).float()  # type: ignore
    freqs_cis = torch.polar(torch.ones_like(freqs), freqs)  # complex64
    return freqs_cis


def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor):
    ndim = x.ndim
    assert 0 <= 1 < ndim
    assert freqs_cis.shape == (x.shape[1], x.shape[-1])
    shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
    return freqs_cis.view(*shape)


def apply_rotary_emb(
    xq: torch.Tensor,
    xk: torch.Tensor,
    freqs_cis: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor]:
    xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
    xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
    print("xq_",xq_.shape)
    freqs_cis = reshape_for_broadcast(freqs_cis, xq_)
    print("freqs_cis",freqs_cis.shape)
    print("freqs_cis_torch.view_as_real",torch.view_as_real(freqs_cis).shape)
    xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
    print("xq_out",xq_out.shape)
    xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
    return xq_out.type_as(xq), xk_out.type_as(xk)

freqs_cis = precompute_freqs_cis(
            4096 // 32, 2048 * 2
        )
# q = torch.randn((2,32,2048,4096//32))
# k = torch.randn((2,32,2048,4096//32))
# v = torch.randn((2,32,2048,4096//32))
q = q.transpose(2,1)
k = k.transpose(2,1)
v = v.transpose(2,1)
freqs_cis_ = freqs_cis[0:2048]
print(f"freqs_cis.shape is {freqs_cis.shape}")
q2, k2 = apply_rotary_emb(q, k, freqs_cis=freqs_cis_)

for i in range(2048):
    print(i,q1.transpose(2,1)[0,i]==q2[0,i])

```
The q1 and q2 exactly match only in position 0. 
That may have some difference.







> > I get different results in the original PR implementation (which had licensing issues) and the current, modified implementation.
> > Using the prompt `This is a story about` and
> > ```
> > output = model.generate(input_ids, do_sample=False)
> > ```
> > 
> > 
> >     
> >       
> >     
> > 
> >       
> >     
> > 
> >     
> >   
> > I get these outputs:
> > ## Original:
> > > This is a story about how we got here, and the challenges ahead.
> > > The first time I saw a drone was in 2013 when my wife and I were visiting our daughter at college. We went to her dorm room one afternoon to drop off some things she needed for class that day, and as soon as we walked into the lobby, there it was: a quadcopter hovering just above us, its four propellers spinning lazily in the air. It wasn’t doing anything special—it was just flying around on its own, like an insect buzzing around your head. But it made me feel uneasy; I didn’t know what to make of this new technology. The next year, after I had moved back home from Washington, D.C., where I worked for a nonprofit, I started noticing them more often while walking through neighborhoods or hiking in the woods. Sometimes they would be parked
> > 
> > 
> > ## Current:
> > > This is a story about a man who was born in the 1920s and lived through the Great Depression, World War II, and the Korean War. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He
> > 
> > 
> > Maybe I am doing something wrong, so can someone double check this?
> 
> me too, there must be something wrong...

<|||||>I had some trouble using the models for batch-mode inference. It seems that the padding token is missing. Below is a possible solution:

```python
tokenizer.pad_token = "[PAD]"
tokenizer.padding_side="left"
batch = ["Yuchen Lin is a ", "Yuchen is a ", "I do not think Yuchen is a"]
inputs = tokenizer(batch, return_tensors="pt", add_special_tokens=False, padding=True)
generated = model.generate(inputs["input_ids"], max_new_tokens=5)
print(tokenizer.decode(generated[1], skip_special_tokens=True))
```<|||||>@marscrazy  it cause `rotate_half` behavior is different than origial(facebookresearch/llama), it is alreay patch by @zphang. 

```
def rotate_half(x):
    """Rotates half the hidden dims of the input."""
    x1 = x[..., : x.shape[-1] // 2]
    x2 = x[..., x.shape[-1] // 2 :]
    return torch.cat((-x2, x1), dim=-1)
```



> > 
> 
> That may be caused by the different ways of rotary position embedding implementation.
> 
> I tried to check the output of rotary embeddings between this pr and raw llama infer code as follows,
> 
> ```
> ### rotary implementation in raw code
> import torch
> class RotaryEmbedding(torch.nn.Module):
>     def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
>         super().__init__()
>         inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
>         self.register_buffer("inv_freq", inv_freq)
> 
>         # Build here to make `torch.jit.trace` work.
>         self.max_seq_len_cached = max_position_embeddings
>         t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
>         freqs = torch.einsum("i,j->ij", t, self.inv_freq)
>         # Different from paper, but it uses a different permutation in order to obtain the same calculation
>         emb = torch.cat((freqs, freqs), dim=-1)
>         self.cos_cached = emb.cos()[None, None, :, :]
>         self.sin_cached = emb.sin()[None, None, :, :]
> 
>     def forward(self, x, seq_len=None):
>         # x: [bs, num_attention_heads, seq_len, head_size]
>         # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
>         if seq_len > self.max_seq_len_cached:
>             self.max_seq_len_cached = seq_len
>             t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
>             freqs = torch.einsum("i,j->ij", t, self.inv_freq)
>             # Different from paper, but it uses a different permutation in order to obtain the same calculation
>             emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
>             self.cos_cached = emb.cos()[None, None, :, :].to(dtype=x.dtype)
>             self.sin_cached = emb.sin()[None, None, :, :].to(dtype=x.dtype)
>         return (
>             self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype, device=x.device),
>             self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype, device=x.device),
>         )
> 
> 
> def rotate_half(x):
>     """Rotates half the hidden dims of the input."""
>     x1 = x[..., : x.shape[-1] // 2]
>     x2 = x[..., : x.shape[-1] // 2]
>     print(x1.shape, x2.shape)
>     return torch.cat((-x2, x1), dim=-1)
> 
> 
> def apply_rotary_pos_emb(q, k, cos, sin, offset: int = 0):
>     cos = cos[..., offset : q.shape[-2] + offset, :]
>     sin = sin[..., offset : q.shape[-2] + offset, :]
>     q_embed = (q * cos) + (rotate_half(q) * sin)
>     k_embed = (k * cos) + (rotate_half(k) * sin)
>     return q_embed, k_embed
> q = torch.randn((2,32,2048,4096//32))
> k = torch.randn((2,32,2048,4096//32))
> v = torch.randn((2,32,2048,4096//32))
> rotary_emb = RotaryEmbedding(4096//32)
> cos, sin = rotary_emb(v, seq_len=2048)
> q1, k1 = apply_rotary_pos_emb(q, k, cos, sin, offset=0)
> 
> ### implementation in this repo
> from typing import Tuple
> def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0):
>     freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
>     t = torch.arange(end, device=freqs.device)  # type: ignore
>     freqs = torch.outer(t, freqs).float()  # type: ignore
>     freqs_cis = torch.polar(torch.ones_like(freqs), freqs)  # complex64
>     return freqs_cis
> 
> 
> def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor):
>     ndim = x.ndim
>     assert 0 <= 1 < ndim
>     assert freqs_cis.shape == (x.shape[1], x.shape[-1])
>     shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
>     return freqs_cis.view(*shape)
> 
> 
> def apply_rotary_emb(
>     xq: torch.Tensor,
>     xk: torch.Tensor,
>     freqs_cis: torch.Tensor,
> ) -> Tuple[torch.Tensor, torch.Tensor]:
>     xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
>     xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
>     print("xq_",xq_.shape)
>     freqs_cis = reshape_for_broadcast(freqs_cis, xq_)
>     print("freqs_cis",freqs_cis.shape)
>     print("freqs_cis_torch.view_as_real",torch.view_as_real(freqs_cis).shape)
>     xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
>     print("xq_out",xq_out.shape)
>     xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
>     return xq_out.type_as(xq), xk_out.type_as(xk)
> 
> freqs_cis = precompute_freqs_cis(
>             4096 // 32, 2048 * 2
>         )
> # q = torch.randn((2,32,2048,4096//32))
> # k = torch.randn((2,32,2048,4096//32))
> # v = torch.randn((2,32,2048,4096//32))
> q = q.transpose(2,1)
> k = k.transpose(2,1)
> v = v.transpose(2,1)
> freqs_cis_ = freqs_cis[0:2048]
> print(f"freqs_cis.shape is {freqs_cis.shape}")
> q2, k2 = apply_rotary_emb(q, k, freqs_cis=freqs_cis_)
> 
> for i in range(2048):
>     print(i,q1.transpose(2,1)[0,i]==q2[0,i])
> ```
> 
> The q1 and q2 exactly match only in position 0. That may have some difference.
> 
> > > I get different results in the original PR implementation (which had licensing issues) and the current, modified implementation.
> > > Using the prompt `This is a story about` and
> > > ```
> > > output = model.generate(input_ids, do_sample=False)
> > > ```
> > > 
> > > 
> > >     
> > >       
> > >     
> > > 
> > >       
> > >     
> > > 
> > >     
> > >   
> > > I get these outputs:
> > > ## Original:
> > > > This is a story about how we got here, and the challenges ahead.
> > > > The first time I saw a drone was in 2013 when my wife and I were visiting our daughter at college. We went to her dorm room one afternoon to drop off some things she needed for class that day, and as soon as we walked into the lobby, there it was: a quadcopter hovering just above us, its four propellers spinning lazily in the air. It wasn’t doing anything special—it was just flying around on its own, like an insect buzzing around your head. But it made me feel uneasy; I didn’t know what to make of this new technology. The next year, after I had moved back home from Washington, D.C., where I worked for a nonprofit, I started noticing them more often while walking through neighborhoods or hiking in the woods. Sometimes they would be parked
> > > 
> > > 
> > > ## Current:
> > > > This is a story about a man who was born in the 1920s and lived through the Great Depression, World War II, and the Korean War. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He was a man who was a part of the greatest generation. He
> > > 
> > > 
> > > Maybe I am doing something wrong, so can someone double check this?
> > 
> > 
> > me too, there must be something wrong...

<|||||>Hi, just want to report that I can't seem to clear the model from the VRAM once it's loaded, tried del, torch.cuda.empty_cache(), gc.collect, nothing seems to work.

Verified in a simple script to load and delete it, so it's not some external factors as far as I can tell.<|||||>Hi, it's a great job! I have read the code provided by meta for inference and also the code for huggingface. I think the module about positional encoding needs to consider the following question. The meta uses the fairscale framework for training. The variables `wk` and `wq` in the `Attention` module use the class `ColumnParallelLinear` in [fairscale](https://github.com/facebookresearch/fairscale/blob/main/fairscale/nn/model_parallel/layers.py#L257). The shape of the `weight` of this class is `(out_dim, in_dim)`, which is the same as `torch.nn.Linear`. When generating `query_states` and `key_states` from `hidden_state`, the actual operation is `x * (weight^T)`, I am not sure whether the `permute()` function used by the author in `convert_llama_weights_to_hf.py` considers to this point. I will post my doubts here first, and I will try it with code later.<|||||>> Hi, it's a great job! I have read the code provided by meta for inference and also the code for huggingface. I think the module about positional encoding needs to consider the following question. The meta uses the fairscale framework for training. The variables `wk` and `wq` in the `Attention` module use the class `ColumnParallelLinear` in [fairscale](https://github.com/facebookresearch/fairscale/blob/main/fairscale/nn/model_parallel/layers.py#L257). The shape of the `weight` of this class is `(out_dim, in_dim)`, which is the same as `torch.nn.Linear`. When generating `query_states` and `key_states` from `hidden_state`, the actual operation is `x * (weight^T)`, I am not sure whether the `permute()` function used by the author in `convert_llama_weights_to_hf.py` considers to this point. I will post my doubts here first, and I will try it with code later.
The following is my code, and the results after running are different except for the shape. Of course, it is also possible that there is a problem with my code.
```python
import torch
import torch.nn.functional as F
in_dim = 8
out_dim = 8
n_head = 1
batch_size = 1
head_dim = in_dim // n_head
seq_len = 2

def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor):
    # x: [bs, seq_len, n_local_heads, head_dim/2]
    ndim = x.ndim
    assert 0 <= 1 < ndim
    # [seq_len, head_dim] == (seq_len, head_dim/2)
    assert freqs_cis.shape == (x.shape[1], x.shape[-1])
    shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
    return freqs_cis.view(*shape)       # -> (1, seq_len, 1, head_dim/2)

def meta(w_q, hidden_state, theta=10000.0):
    xq = F.linear(hidden_state, w_q)
    freqs = 1.0 / (theta ** (torch.arange(0, head_dim, 2)[: (head_dim // 2)].float() / head_dim))
    t = torch.arange(seq_len)
    freqs = torch.outer(t, freqs).float()
    freqs_cis = torch.polar(torch.ones_like(freqs), freqs)      # [seq_len, head_dim/2]
    xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
    freqs_cis = reshape_for_broadcast(freqs_cis, xq_)
    xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
    print("meta:")
    print(xq_out)
    print(xq_out.shape)

# ----------------------------------------------------------------
"""store cos(mθ) and sin(mθ)"""
class LlamaRotaryEmbedding(torch.nn.Module):
    def __init__(self, dim, max_position_embeddings=seq_len, base=10000, device=None):
        super().__init__()
        """dim == head_dim"""
        # inv_freq.shape == (dim/2)
        inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
        self.register_buffer("inv_freq", inv_freq)

        # Build here to make `torch.jit.trace` work.
        self.max_seq_len_cached = max_position_embeddings

        # t.shape == (seq_len)
        t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)

        # t*inv_freq^T
        # freqs.shape == (seq_len, dim/2)
        freqs = torch.einsum("i,j->ij", t, self.inv_freq)

        # Different from paper, but it uses a different permutation in order to obtain the same calculation
        # emb.shape == (seq_len, dim)
        emb = torch.cat((freqs, freqs), dim=-1)

        # sim_cached == cos_cached.shape == (1, 1, seq_len, dim)
        self.cos_cached = emb.cos()[None, None, :, :]
        self.sin_cached = emb.sin()[None, None, :, :]

    def forward(self, x, seq_len=None):
        # x: [bs, num_attention_heads, seq_len, head_size]
        # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
        return (
            self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype, device=x.device),
            self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype, device=x.device),
        )

"""used by apply_rotary_pos_emb()"""
def rotate_half(x):
    """Rotates half the hidden dims of the input."""
    """x: (bs, num_head, seq_len, head_dim)"""
    x1 = x[..., : x.shape[-1] // 2]
    x2 = x[..., x.shape[-1] // 2 :]
    return torch.cat((-x2, x1), dim=-1)

def apply_rotary_pos_emb(q, cos, sin, offset: int = 0):
    """

    :param q:  Query (bs, num_head, seq_len, head_dim)
    :param k:  Key   (bs, num_head, seq_len, head_dim)
    :param cos:      (1, 1, seq_len, head_dim)
    :param sin:      (1, 1, seq_len, head_dim)
    :param offset:   0
    :return:
    """
    cos = cos[..., offset : q.shape[-2] + offset, :]
    sin = sin[..., offset : q.shape[-2] + offset, :]
    q_embed = (q * cos) + (rotate_half(q) * sin)
    return q_embed

def hf(w_q, hidden_state):
    def permute(w):
        return w.view(n_head, in_dim // n_head // 2, 2, in_dim).transpose(1, 2).reshape(in_dim, in_dim)
    w_q = permute(w_q)          # convert_llama_weights_to_hf.py
    linear = torch.nn.Linear(in_dim, n_head*head_dim)
    linear.weight.data = w_q
    xq = linear(hidden_state)
    rotary_emb = LlamaRotaryEmbedding(head_dim)
    cos, sin = rotary_emb(xq, seq_len=seq_len)
    query_states = apply_rotary_pos_emb(xq, cos, sin, offset=0)
    print("huggingface:")
    print(query_states)
    print(query_states.shape)

if __name__ == '__main__':
    w_q = torch.rand([out_dim, head_dim])
    hidden_state = torch.rand([batch_size, seq_len, n_head, head_dim])
    meta(w_q, hidden_state)
    hf(w_q, hidden_state)
```<|||||>Inference is OK, however the result seems not understandable.
![image](https://user-images.githubusercontent.com/26135691/225562507-7072f4c8-6e46-4e0b-8eea-a934d6f0c4e9.png)
<|||||>Thanks again for all your work @zphang ! Merging this now and we can continue iterating if there are standing bugs in followups PRs (as we discussed, will ping you on a PR for the conversion script and I have a couple more nits but don't want to hold the merge for them).

For anyone still having an issue with the model, I encourage you to create a new issue with a clear reproducer (after checking your bug still exists on the main branch of course). Thanks in advance!<|||||>For some reason, GitHub is not marking this PR as closed even if it has been merged (it sees it merged twice cause I clicked the button twice...). Closing manually, but the (first) [merge commit](https://github.com/huggingface/transformers/commit/0041be5b3d1b9a5e1443e1825d7d80f6dfadcdaa) is here.<|||||>@ longzhang418
> Hello, I have a question about training llama. Does the current version of training not support the zero strategy of deepspeed? I added the deepspeed configuration file, but it doesn't seem to take effect. Looking for your reply, thank you~

Hi, we success use accelerate with ds_3_zero3_offload policy to train llama-13B in 4 A100s with memory 80GB(batch size=16 length=256 works for us ), firstly transfer 13B weights into hf weights format, then our accelerate config is in below:

> compute_environment: LOCAL_MACHINE
deepspeed_config:
  gradient_accumulation_steps: 1
  gradient_clipping: 1.0
  offload_optimizer_device: 'cpu'
  offload_param_device: none
  zero3_init_flag: true
  zero3_save_16bit_model: true
  zero_stage: 3
distributed_type: DEEPSPEED
downcast_bf16: 'no'
dynamo_backend: 'NO'
fsdp_config: {}
machine_rank: 0
main_training_function: main
megatron_lm_config: {}
mixed_precision: 'fp16'
num_machines: 1
num_processes: 4
rdzv_backend: static
same_network: true
use_cpu: false

The fsdp should works too, as the impl in standford repo.
significantly, we test 13B with ds0/ds1/ds2 on one A100 all failed because of CUDA memory.

Finally we failed on test some model pipeline methods, eg. fairscale pp, it's the next thing we need to do.

<|||||>What's the motivation for the three special tokens `tokenizer.pad_token, tokenizer.bos_token, tokenizer.eos_token = '' `  [when converting the llama tokenizer?](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/convert_llama_weights_to_hf.py#L243)<|||||>> What's the motivation for the three special tokens `tokenizer.pad_token, tokenizer.bos_token, tokenizer.eos_token = '' ` [when converting the llama tokenizer?](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/convert_llama_weights_to_hf.py#L243)

Yeah, I am also quite confused. And I noticed even with `add_special_tokens=True`, LlamaTokenizer will not append an EOS token explicitly. <|||||>Just started working on a fix for the tokenizer conversion, will link the PR asap: #22402<|||||>what's the version of huggingface-transformers for LLaMa ?
<|||||>When I am converting the llama to hf format (using convert_llama_weights_to_hf.py), each part of layer is the same size as the whole file
is anyone who met the same issue before?

```bash
python convert_llama_weights_to_hf.py  --input_dir models/ --model_size 7B --output_dir llama/fp32/
```

the subfiles (it  is processing):

```bash
-rw-rw-r--. 1 wyd anaconda  26G Apr 12 15:55 pytorch_model-1-of-33.bin
-rw-rw-r--. 1 wyd anaconda  26G Apr 12 15:59 pytorch_model-2-of-33.bin
-rw-rw-r--. 1 wyd anaconda 129M Apr 12 15:59 pytorch_model-3-of-33.bin
```
the raw file:

```bash
-rw-rw-r--. 1 wyd anaconda  26G Apr 12 15:50 consolidated.00.fp32.pth
```

it's going right when i converted the llama to fp16.<|||||>I think there might be something off with this model and tokenizer https://discuss.huggingface.co/t/llamatokenizerfast-returns-token-type-ids-but-the-forward-pass-of-the-llamamodel-does-not-receive-token-type-ids/42431 could someone take a look?<|||||>Hey! Yes this is fixed by #24042 