# Custom 4D attention masks in training OOM

**URL:** </static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fcustom-4d-attention-masks-in-training-oom%2F107420%3E%5C
**Category:** 🤗Transformers\
**Created:** [September 19, 2024, 9:58pm UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fcustom-4d-attention-masks-in-training-oom%2F107420 "2024-09-19T21:58:04Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![jpcorb20](https://avatars.discourse-cdn.com/v4/letter/j/f4b2a3/32.png) [@jpcorb20](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2Fjpcorb20)%5C
**Post date:** [September 19, 2024, 9:58pm UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fcustom-4d-attention-masks-in-training-oom%2F107420%2F1 "2024-09-19T21:58:04Z")

</div>

I am trying to do packing with 4d attention masks with Phi3-mini-4k-instruct to delimit attention only to unique sequences in one packed sequence, but I always get OOM… Any advice on this? Could we get an example of usage?

---

<div class="post-metadata">

**Author:** ![jpcorb20](https://avatars.discourse-cdn.com/v4/letter/j/f4b2a3/32.png) [@jpcorb20](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2Fjpcorb20)%5C
**Post date:** [September 24, 2024, 8:41pm UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fcustom-4d-attention-masks-in-training-oom%2F107420%2F2 "2024-09-24T20:41:33Z")

</div>

pretty much similar to the packing here: [4D masks support in Transformers (huggingface.co)](https://huggingface.co/blog/poedator/4d-masks)

---

<div class="post-metadata">

**Author:** ![John6666](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/john6666/32/27664_2.png) [@John6666](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2FJohn6666)%5C
**Post date:** [September 24, 2024, 10:39pm UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fcustom-4d-attention-masks-in-training-oom%2F107420%2F3 "2024-09-24T22:39:45Z")

</div>

What can I say…  
I can hardly find any examples of actual operation. I think the library is still underdeveloped in general for that application.

> <https://github.com/huggingface/transformers/issues/32101>
>
> \### System Info
> 
> transformers 4.41.0
> 
> \### Who can help?
> 
> …@ArthurZucker
> 
> \### Information
> 
> \- \[\] The official example scripts
> \- \[X\] My own modified scripts
> 
> \### Tasks
> 
> \- \[\] An officially supported task in the \`examples\` folder (such as GLUE/SQuAD, ...)
> \- \[X\] My own task or dataset (give details below)
> 
> \### Reproduction
> 
> \`\`\`
> from transformers import LlamaForCausalLM, LlamaConfig, TrainingArguments, Trainer, AutoTokenizer
> from datasets import IterableDataset
> import numpy as np
> 
> model\_config = LlamaConfig(
> vocab\_size=10,
> hidden\_size=384,
> num\_hidden\_layers=6,
> num\_attention\_heads=6,
> intermediate\_size=1024,
> max\_position\_embeddings=1024,
> )
> model = LlamaForCausalLM(model\_config)
> tokenizer = AutoTokenizer.from\_pretrained('facebook/opt-125m')
> 
> def get\_data1():
> for i in range(10000):
> yield {'input\_ids': np.zeros(1024, dtype=int), 'labels': np.zeros(1024, dtype=int), 'attention\_mask': np.zeros((1, 1024, 1024), dtype=float)}
> 
> def get\_data2():
> for i in range(10000):
> yield {'input\_ids': np.zeros(1024, dtype=int), 'labels': np.zeros(1024, dtype=int), 'attention\_mask': np.zeros((1024), dtype=int)}
>     
> ds\_slow = IterableDataset.from\_generator(get\_data1).with\_format('torch')
> ds\_fast = IterableDataset.from\_generator(get\_data2).with\_format('torch')
> 
> training\_args = TrainingArguments(max\_steps=1, output\_dir='./out', report\_to=None, per\_device\_train\_batch\_size=32, gradient\_accumulation\_steps=32)
> trainer1 = Trainer(model, training\_args, train\_dataset=ds\_slow, tokenizer=tokenizer)
> trainer2 = Trainer(model, training\_args, train\_dataset=ds\_fast, tokenizer=tokenizer)
> 
> import cProfile
> cProfile.run('trainer1.train()', './test\_slow.profile')
> cProfile.run('trainer2.train()', './test\_fast.profile')
> \`\`\`
> 
> \`\`\`
> import pstats
> 
> \# compare the two profiles
> p1 = pstats.Stats('./test\_slow.profile')
> p2 = pstats.Stats('./test\_fast.profile')
> p1.sort\_stats('cumtime').print\_stats()
> \`\`\`
> \`\`\`
> 1582200 function calls (1401111 primitive calls) in 340.112 seconds
> 
> Ordered by: cumulative time
> 
> ncalls tottime percall cumtime percall filename:lineno(function)
> 1 0.000 0.000 340.112 340.112 {built-in method builtins.exec}
> 1 0.000 0.000 340.112 340.112 \<string\>:1(\<module\>)
> 1 0.000 0.000 340.112 340.112 trainer.py:1784(train)
> 1 0.017 0.017 340.112 340.112 trainer.py:1892(\_inner\_training\_loop)
> 33 0.001 0.000 326.171 9.884 data\_loader.py:663(\_\_iter\_\_)
> 33 0.001 0.000 325.473 9.863 data\_loader.py:618(\_fetch\_batches)
> 2486/265 0.001 0.000 325.428 1.228 {built-in method builtins.next}
> 33 0.001 0.000 325.088 9.851 dataloader.py:625(\_\_next\_\_)
> 33 0.725 0.022 325.083 9.851 dataloader.py:672(\_next\_data)
> 33 0.002 0.000 323.988 9.818 fetch.py:24(fetch)
> 33 0.000 0.000 320.979 9.727 trainer\_utils.py:807(\_\_call\_\_)
> 33 0.000 0.000 320.971 9.726 data\_collator.py:270(\_\_call\_\_)
> 33 16.982 0.515 320.971 9.726 data\_collator.py:52(pad\_without\_fast\_tokenizer\_warning)
> 33 0.005 0.000 303.989 9.212 tokenization\_utils\_base.py:3209(pad)
> 6493 235.747 0.036 235.747 0.036 {built-in method torch.tensor}
> 197 0.001 0.000 234.735 1.192 tokenization\_utils\_base.py:204(\_\_init\_\_)
> 197 0.001 0.000 234.732 1.192 tokenization\_utils\_base.py:681(convert\_to\_tensors)
> 99 0.000 0.000 234.730 2.371 tokenization\_utils\_base.py:718(as\_tensor)
> \`\`\`
> 
> \`\`\`
> p2.sort\_stats('cumtime').print\_stats()
> \`\`\`
> 
> \`\`\`
> 1567440 function calls (1386340 primitive calls) in 16.431 seconds
> 
> Ordered by: cumulative time
> 
> ncalls tottime percall cumtime percall filename:lineno(function)
> 1 0.000 0.000 16.431 16.431 {built-in method builtins.exec}
> 1 0.000 0.000 16.431 16.431 \<string\>:1(\<module\>)
> 1 0.000 0.000 16.431 16.431 trainer.py:1784(train)
> 1 0.018 0.018 16.431 16.431 trainer.py:1892(\_inner\_training\_loop)
> 32 0.003 0.000 14.327 0.448 trainer.py:3212(training\_step)
> 32 0.001 0.000 8.830 0.276 accelerator.py:2093(backward)
> 32 0.000 0.000 8.829 0.276 \_tensor.py:433(backward)
> 32 0.000 0.000 8.829 0.276 \_\_init\_\_.py:149(backward)
> 32 8.827 0.276 8.827 0.276 {method 'run\_backward' of 'torch.\_C.\_EngineBase' objects}
> 33 0.000 0.000 4.546 0.138 memory.py:147(empty\_cache)
> 33 4.546 0.138 4.546 0.138 {built-in method torch.\_C.\_cuda\_emptyCache}
> 2486/265 0.001 0.000 1.469 0.006 {built-in method builtins.next}
> 33 0.001 0.000 1.160 0.035 data\_loader.py:663(\_\_iter\_\_)
> 33 0.000 0.000 1.145 0.035 data\_loader.py:618(\_fetch\_batches)
> 33 0.000 0.000 1.136 0.034 dataloader.py:625(\_\_next\_\_)
> 33 0.003 0.000 1.134 0.034 dataloader.py:672(\_next\_data)
> 33 0.002 0.000 1.124 0.034 fetch.py:24(fetch)
> 32 0.000 0.000 0.955 0.030 trainer.py:3254(compute\_loss)
> ...
> 1 0.000 0.000 0.000 0.000 modeling\_utils.py:903(\_
> ...
> \`\`\`
> 
> \### Expected behavior
> 
> Since the trace of the profiler is really long I only included the first few lines. 
> I am running a small llama model on some dummy data, the only difference between the two datasets is that the slow version outputs 4D attention masks, which is a feature recently added in #27539. I am running both trainers for 1 iteration.
> 
> As you can see the slow run is 340s while the fast one runs in 16s. 
> 
> The slow version of the trainer is many times slower than the fast version. The problem probably lies in the default collator \`DataCollatorWithPadding\` (when there is a pretrained tokenizer), which calls \`tokenizer.pad\` on the 4D attention masks. When you takeaway either 1) the pretrained tokenizer or 2) the 4D attention mask, trainer runs much faster.

> <https://github.com/huggingface/transformers/issues/29525>
>
> \### System Info
> 
> The 4.38.2 version breaks code using custom 4d attention mask…s (introduced in #27539). Apparently, the custom masks gets replaced here:https://github.com/huggingface/transformers/blob/4ed9ae623d16876ad84ea89dfdf1c9378e36961b/src/transformers/models/llama/modeling\_llama.py#L660-L662
> 
> The issue was introduced with #28937. It is unclear whether the relevant slow tests for 4d masks were run then, but they fail now:
> \`\`\`
> RUN\_SLOW=1 python -m pytest -v ./tests/test\_modeling\_utils.py::Mask4DTestFP32
> FAILED tests/test\_modeling\_utils.py::Mask4DTestFP32::test\_attention - AttributeError: 'NoneType' object has no attribute 'shape'
> FAILED tests/test\_modeling\_utils.py::Mask4DTestFP32::test\_causal\_model\_logits - AssertionError: Tensor-likes are not close!
> FAILED tests/test\_modeling\_utils.py::Mask4DTestFP32::test\_inner\_model - AssertionError: Tensor-likes are not close!
> 
> RUN\_SLOW=1 python -m pytest -v ./tests/test\_modeling\_utils.py::Mask4DTestFP16
> FAILED tests/test\_modeling\_utils.py::Mask4DTestFP16::test\_attention - AttributeError: 'NoneType' object has no attribute 'shape'
> FAILED tests/test\_modeling\_utils.py::Mask4DTestFP16::test\_causal\_model\_logits - AssertionError: Tensor-likes are not close!
> \`\`\`
> please fix or suggest workaround
> 
> summoning @ArthurZucker 
> cc @gante @younesbelkada

---

<div class="post-metadata">

**Author:** ![jpcorb20](https://avatars.discourse-cdn.com/v4/letter/j/f4b2a3/32.png) [@jpcorb20](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2Fjpcorb20)%5C
**Post date:** [September 25, 2024, 2:36pm UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fcustom-4d-attention-masks-in-training-oom%2F107420%2F4 "2024-09-25T14:36:35Z")

</div>

Indeed, thanks for sharing these issues. Since my version is quite recent (4.40.2), I don’t think the second would apply … For more context, I am seeing OOM of hundreds of gigabits which actually does not make sense, I tried to reduce batch size and other memory strategies without success. If I change my attention masks to regular ones, it works fine … which I dont understand since behind the scene they should convert into 4d as well based on what I have seen in the codebase.

---

<div class="post-metadata">

**Author:** ![John6666](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/john6666/32/27664_2.png) [@John6666](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2FJohn6666)%5C
**Post date:** [September 25, 2024, 2:52pm UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fcustom-4d-attention-masks-in-training-oom%2F107420%2F5 "2024-09-25T14:52:43Z")

</div>

> OOM of hundreds of gigabits which actually does not make sense,

I don’t know if it’s your code, your model, or the HF library, but something is definitely wrong.😅

I’d say it’s most likely the HF library. The next best thing would be options to pass to the library. Like data type or device specification. Rare case is torch, since there shouldn’t be any major changes now.  
I don’t think it would take much more than a wrong model structure to do that, and it’s hard to find a case where a mistake in the code would do that, unless it was intentional.  
Articles are usually written assuming a github version, so I think you should pip install git+. It’s so-so, there are frequent bugs, but no real harm unless it’s commercial. Also, in a GPU environment, the presence or absence of the accelerate library, its version, and the state of bugs can have a big impact. I would not install the development version of this because I’m afraid to do so.

---

<div class="post-metadata">

**Author:** ![jpcorb20](https://avatars.discourse-cdn.com/v4/letter/j/f4b2a3/32.png) [@jpcorb20](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2Fjpcorb20)%5C
**Post date:** [October 5, 2024, 8:31pm UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fcustom-4d-attention-masks-in-training-oom%2F107420%2F6 "2024-10-05T20:31:24Z")

</div>

Looks like it might be related to flash attention 2 implementation, especially how it is implemented for Phi3 … When I am switching to eager attention, it is starting, but much less efficient. Is someone familiar with how to adapt flash attention 2 to custom 4d masks?

---

<div class="post-metadata">

**Author:** ![John6666](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/john6666/32/27664_2.png) [@John6666](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2FJohn6666)%5C
**Post date:** [October 6, 2024, 12:36am UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fcustom-4d-attention-masks-in-training-oom%2F107420%2F7 "2024-10-06T00:36:25Z")

</div>

> **[microsoft/Phi-3-vision-128k-instruct · Unable to load the model](https://huggingface.co/microsoft/Phi-3-vision-128k-instruct/discussions/10)**
>
> Hi, I'm following the tuto, installed all libs requiered (including flash\_attn), but I cannot load the model:

> **[Improving Hugging Face Training Efficiency Through Packing with Flash...](https://huggingface.co/blog/packing-with-FA2)**
>
> We’re on a journey to advance and democratize artificial intelligence through open source and open science.

It would be faster to find an HF account of someone who seems to know more and send a mention (@+username). Or we can look for other ways to speed up the process.

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/hellohellohello/original/2X/d/de4155eb4aa4108ecb32a1389d7cc37ae69f88b7.png) [@system](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2Fsystem)%5C
**Post date:** [October 7, 2024, 1:21pm UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fcustom-4d-attention-masks-in-training-oom%2F107420%2F8 "2024-10-07T13:21:42Z")

</div>

Closed on October 7, 2024, 1:21pm UTC

This topic was automatically closed 12 hours after the last reply. New replies are no longer allowed.
