🚨 [v5] Refactor RoPE for layer types
Author: zucchini-nlp
Pull request: yes
Labels: name: for_v5?

# What does this PR do?

This PR enables rope layers to compute different frequencies for different layer types, which will help us to support models like ModernBert without monkey patching config on-the-fly

Main changes:
- In config classes the `rope_parameters` is a required attribute if model has RoPE layers. The attr must be a dict containing `rope_theta` and optionally other parameters to configure rope. In case we want different params per layer type, it should be a nested dict of format `{"full_attn": {**rope_params}, "sliding_attn": {**different_rope_params}}`
- The config attr `rope_scaling` is deprecated in favor of `rope_parameters` and raises warning. The latter name is more descriptive
- Default rope freq computation is moved to the model definition similar to `eager_attention_forward`, and copied with modular in each file
- RoPE layer now looks for layer types in the config and computes `inv_freq` for each type. If the given layer types has no rope parameters saved in config (e.g. `config.rope_scaling` has no key=="sliding_window") we raise an error
- All models copy from rope layers llama when possible, so that changing one file will update it everywhere. Models with layer types copy from gemma2
- Config classes now have typing hint in all language models and the rope scaling attribute is typed with  `TypedDict`. It will make our lives easier when we decide to enforce strict type validation on configs

The changes are BC and we will support old-format config files, and standardize it when initializing the config class. The best way to review is to start from `modeling_rope_utils.py` -> `all llama model files` -> `gemma2 and gemma33 model files` -> `tests`

Comments:
The docs for this PR live [here](https://moon-ci-docs.huggingface.co/docs/transformers/pr_39847). All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

run-slow: arcee, aria, bamba, bitnet, chameleon, cohere, cohere2, csm, dbrx, deepseek_v2, deepseek_v3, dia, diffllaama, doge, llama, gemma, gemma2, gemma3, phi3, phimoe, granitemoe, modernbert, modernbert_decoder, qwen2_vl, glm4v, moonshine

This comment contains run-slow, running the specified jobs: 

models: ['models/arcee', 'models/aria', 'models/bamba', 'models/bitnet', 'models/chameleon', 'models/cohere', 'models/cohere2', 'models/csm', 'models/dbrx', 'models/deepseek_v2', 'models/deepseek_v3', 'models/dia', 'models/doge', 'models/gemma', 'models/gemma2', 'models/gemma3', 'models/glm4v', 'models/granitemoe', 'models/llama', 'models/modernbert', 'models/modernbert_decoder', 'models/moonshine', 'models/phi3', 'models/phimoe', 'models/qwen2_vl']
quantizations: [] ...

@ydshieh can we run a full CI on this branch, as it changes a lot of models and I want to see which tests will be failing before it's merged/reviewed

@ArthurZucker if you have time to start reviewing. It is all done except for a few test cases to fix. I suggest to start from `modeling_rope_utils.py` and Llama, Gemma3, ModentBert as models with different RoPE types 

Some models have unrelated changes due to fixup such as using new attn API or mask API.

@zucchini-nlp did you benchmark this now that we re-compute? 
TBH I am a lot more in favor of computing at the layer level only when it is actually needed vs all the time!

this will mean less changes and more granularity but might be hard with the modular? 


> @zucchini-nlp did you benchmark this now that we re-compute?
> TBH I am a lot more in favor of computing at the layer level only when it is actually needed vs all the time!

I asked Joao who did the first PR moving RoPE from layer-wise to model, and he told me the wins are super tiny. Also, I want to stress that having one RoPE layer per model means we would need more breaking changes. I made a draft for that version as well before working on this PR, and it is linked on PR description above

run-slow: gemma3, modernbert, modernbert_decoder, llama, qwen2_vl, efficientlotr, mistral

This comment contains run-slow, running the specified jobs: 

models: ['models/gemma3', 'models/llama', 'models/mistral', 'models/modernbert', 'models/modernbert_decoder', 'models/qwen2_vl']
quantizations: [] ...

>  he told me the wins are super tiny
I know! But I think we gotta be thorough and provide benches here for the community! 

@ArthurZucker running generation with Llama of different sizes for 128 tokens, below are plots for latency per token. 

| RoPE           | Model                      | Latency per Token |
|----------------|----------------------------|-------------------|
| per-layer RoPE | Llama-3.2-1B               | 0.020978          |
| per-layer RoPE | Llama-3.2-3B-Instruct      | 0.035719          |
| per-layer RoPE | Meta-Llama-3-8B-Instruct   | 0.041517          |
| per-model RoPE | Llama-3.2-1B               | 0.017331          |
| per-model RoPE | Llama-3.2-3B-Instruct      | 0.029626          |
| per-model RoPE | Meta-Llama-3-8B-Instruct   | 0.034352          |

<details>
<summary>Expand for bench plots</summary>

<img width="1200" height="600" alt="plot_llama8b" src="https://github.com/user-attachments/assets/ac336f92-5aae-4573-a92f-e5caf79da285" />
<img width="1200" height="600" alt="plot_llama3b" src="https://github.com/user-attachments/assets/616ea859-dd76-4914-bf68-bcdc3db42149" />
<img width="1200" height="600" alt="plot_llama1b" src="https://github.com/user-attachments/assets/09e6654a-6dcf-423f-a2dd-09b69db44324" />

</details>


<details>
<summary>Expand for bench script</summary>

```python
import torch
import torch.utils.benchmark as benchmark
from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed

set_seed(123)
FRANCE_ARTICLE = """
Marseille, France (CNN)The French prosecutor leading an investigation into the crash of Germanwings Flight 9525 insisted Wednesday that he was not aware of any video footage from on board the plane. Marseille prosecutor Brice Robin told CNN that "so far no videos were used in the crash investigation." He added, "A person who has such a video needs to immediately give it to the investigators." Robin\'s comments follow claims by two magazines, German daily Bild and French Paris Match, of a cell phone video showing the harrowing final seconds from on board Germanwings Flight 9525 as it crashed into the French Alps. All 150 on board were killed. Paris Match and Bild reported that the video was recovered from a phone at the wreckage site. The two publications described the supposed video, but did not post it on their websites. The publications said that they watched the video, which was found by a source close to the investigation. \"One can hear cries of 'My God' in several languages,\" Paris Match reported. "Metallic banging can also be heard more than three times, perhaps of the pilot trying to open the cockpit door with a heavy object.  Towards the end, after a heavy shake, stronger than the others, the screaming intensifies. Then nothing." "It is a very disturbing scene," said Julian Reichelt, editor-in-chief of Bild online. An official with France's accident investigation agency, the BEA, said the agency is not aware of any such video. Lt. Col. Jean-Marc Menichini, a French Gendarmerie spokesman in charge of communications on rescue efforts around the Germanwings crash site, told CNN that the reports were "completely wrong" and "unwarranted." Cell phones have been collected at the site, he said, but that they "hadn\'t been exploited yet." Menichini said he believed the cell phones would need to be sent to the Criminal Research Institute in Rosny sous-Bois, near Paris, in order to be analyzed by specialized technicians working hand-in-hand with investigators. But none of the cell phones found so far have been sent to the institute, Menichini said. Asked whether staff involved in the search could have leaked a memory card to the media, Menichini answered with a categorical "no." Reichelt told "Erin Burnett: Outfront" that he had watched the video and stood by the report, saying Bild and Paris Match are "very confident" that the clip is real. He noted that investigators only revealed they\'d recovered cell phones from the crash site after Bild and Paris Match published their reports. "That is something we did not know before. ... Overall we can say many things of the investigation weren't revealed by the investigation at the beginning," he said. What was mental state of Germanwings co-pilot? German airline Lufthansa confirmed Tuesday that co-pilot Andreas Lubitz had battled depression years before he took the controls of Germanwings Flight 9525, which he's accused of deliberately crashing last week in the French Alps. Lubitz told his Lufthansa flight training school in 2009 that he had a "previous episode of severe depression," the airline said Tuesday. Email correspondence between Lubitz and the school discovered in an internal investigation, Lufthansa said, included medical documents he submitted in connection with resuming his flight training. The announcement indicates that Lufthansa, the parent company of Germanwings, knew of Lubitz's battle with depression, allowed him to continue training and ultimately put him in the cockpit. Lufthansa, whose CEO Carsten Spohr previously said Lubitz was 100% fit to fly, described its statement Tuesday as a "swift and seamless clarification" and said it was sharing the information and documents -- including training and medical records -- with public prosecutors. Spohr traveled to the crash site Wednesday, where recovery teams have been working for the past week to recover human remains and plane debris scattered across a steep mountainside. He saw the crisis center set up in Seyne-les-Alpes, laid a wreath in the village of Le Vernet, closer to the crash site, where grieving families have left flowers at a simple stone memorial. Menichini told CNN late Tuesday that no visible human remains were left at the site but recovery teams would keep searching. French President Francois Hollande, speaking Tuesday, said that it should be possible to identify all the victims using DNA analysis by the end of the week, sooner than authorities had previously suggested. In the meantime, the recovery of the victims' personal belongings will start Wednesday, Menichini said. Among those personal belongings could be more cell phones belonging to the 144 passengers and six crew on board. Check out the latest from our correspondents . The details about Lubitz's correspondence with the flight school during his training were among several developments as investigators continued to delve into what caused the crash and Lubitz's possible motive for downing the jet. A Lufthansa spokesperson told CNN on Tuesday that Lubitz had a valid medical certificate, had passed all his examinations and "held all the licenses required." Earlier, a spokesman for the prosecutor\'s office in Dusseldorf, Christoph Kumpa, said medical records reveal Lubitz suffered from suicidal tendencies at some point before his aviation career and underwent psychotherapy before he got his pilot's license. Kumpa emphasized there's no evidence suggesting Lubitz was suicidal or acting aggressively before the crash. Investigators are looking into whether Lubitz feared his medical condition would cause him to lose his pilot's license, a European government official briefed on the investigation told CNN on Tuesday. While flying was "a big part of his life," the source said, it\'s only one theory being considered. Another source, a law enforcement official briefed on the investigation, also told CNN that authorities believe the primary motive for Lubitz to bring down the plane was that he feared he would not be allowed to fly because of his medical problems. Lubitz's girlfriend told investigators he had seen an eye doctor and a neuropsychologist, both of whom deemed him unfit to work recently and concluded he had psychological issues, the European government official said. But no matter what details emerge about his previous mental health struggles, there's more to the story, said Brian Russell, a forensic psychologist. "Psychology can explain why somebody would turn rage inward on themselves about the fact that maybe they weren't going to keep doing their job and they're upset about that and so they're suicidal," he said. "But there is no mental illness that explains why somebody then feels entitled to also take that rage and turn it outward on 149 other people who had nothing to do with the person's problems." Germanwings crash compensation: What we know . Who was the captain of Germanwings Flight 9525? CNN's Margot Haddad reported from Marseille and Pamela Brown from Dusseldorf, while Laura Smith-Spark wrote from London. CNN's Frederik Pleitgen, Pamela Boykoff, Antonia Mortensen, Sandrine Amiel and Anna-Maja Rappard contributed to this report.""" * 40

model_ids = ["meta-llama/Llama-3.2-1B", "meta-llama/Llama-3.2-3B-Instruct", "meta-llama/Meta-Llama-3-8B-Instruct"]

results = []
for model_id in model_ids:
	tokenizer = AutoTokenizer.from_pretrained(model_id)
	model = AutoModelForCausalLM.from_pretrained(model_id, device_map="cuda", torch_dtype="bfloat16")
	model.generation_config.pad_token_id = tokenizer.eos_token_id

	WHOLE_INPUT = tokenizer([FRANCE_ARTICLE]*10, return_tensors="pt").to(model.device).input_ids

	for bs in [1, 2, 5, 10]:
		for seq_length in [1, 512, 1024, 2048]:
			input_ids = WHOLE_INPUT[:bs, :seq_length]

			# warmup
			for _ in range(3):
				genereted = model.generate(input_ids, use_cache=True, min_new_tokens=128, max_new_tokens=128)

			bench_result = benchmark.Timer(
				stmt="model.generate(input_ids, use_cache=True, min_new_tokens=128, max_new_tokens=128)",
				globals={
					"input_ids": input_ids,
					"model": model,
				},
				description="Generate with per-layer RoPE",
				label=f"{model_id}",
				sub_label=f"BS={bs} and seq_length={seq_length}",
			)
			results.append(bench_result.blocked_autorange())

compare = benchmark.Compare(results)
compare.trim_significant_figures()
compare.colorize()
compare.print()
```
</details>

Nice benches, sorry for my late notice! It seems significant enough to not want to do it on a per layer basis 

Finally, this PR is ready for first review. Pinging @gante for it, and if you are happy I'll ping Arthur :)

> Reminder: the best way to review is to start from modeling_rope_utils.py -> all llama model files -> gemma3 model files -> tests

Rebasing caused test failures again 😢 

Test failures don't seem related

What? Why so many conflicts, I just finished merging main and fixing tests again... 😢 

I think this can be reviewed again @gante . I separated RoPE layer to two types, ones is llama-like and the other gemma2-like with layer types. I added small doc on rope utilities and we can add more information on it later

I'd love to merge this soon, the merge conflicts are appearing several times a day and making the PR unmanageable 

☠️ will review asap, and hold back nits. Merge conflicts are the worst 😢 

Thanks, i will merge main now and some MoE tests seems to be failing still

CI is green, wow 🎉  

☠️ 🫂 

<img width="281" height="67" alt="Screenshot 2025-10-11 at 11 49 56" src="https://github.com/user-attachments/assets/0960ffd0-3901-45f5-8cc0-e4431b3c8dfe" />


run-slow: llama, gemma2, modernbert, qwen2, cohere2, llava, gemma3, mistral, qwen2_vl, qwen2_5_omni

This comment contains run-slow, running the specified jobs: 

models: ['models/cohere2', 'models/gemma2', 'models/gemma3', 'models/llama', 'models/llava', 'models/mistral', 'models/modernbert', 'models/qwen2', 'models/qwen2_5_omni', 'models/qwen2_vl']
quantizations: [] ...

> So as always, let's revert the changes for models that don't have many layer types, let's make sure we only modify the relevant models (but the wrapper of dynamic is very !)

It is already done 😄  Only models with layer types have different RoPE and they usually use Gemma2 as modular. Other models use Llama

run-slow: apertus

run-slow: vit

This comment contains run-slow, running the specified jobs: 

models: ['models/vit']
quantizations: [] ...

run-slow: gpt2, qwen2_vl, gemma3, llama, mistral, llava, lfm2_vl

This comment contains run-slow, running the specified jobs: 

models: ['models/gemma3', 'models/gpt2', 'models/lfm2_vl', 'models/llama', 'models/llava', 'models/mistral', 'models/qwen2_vl']
quantizations: [] ...

**[For maintainers]** Suggested jobs to run (before merge)

run-slow: apertus, arcee, aria, bamba, bitnet, blt, chameleon, cohere

Visually inspected first ~20 models, for the rest I trust in our testing suite. Will fix a few inconsistencies and merge tomorrow

run-slow: gpt2, qwen2_vl, gemma3, llama, mistral, llava, lfm2_vl, olmo, gemma, paligemma, qwen2_5_omni

**[For maintainers]** Suggested jobs to run (before merge)

run-slow: apertus, arcee, aria, bamba, bitnet, blt, chameleon

Just to be sure, let the slow CI run on some important models

This comment contains run-slow, running the specified jobs: 

models: ['models/gemma', 'models/gemma3', 'models/gpt2', 'models/lfm2_vl', 'models/llama', 'models/llava', 'models/mistral', 'models/olmo', 'models/paligemma', 'models/qwen2_5_omni', 'models/qwen2_vl']
quantizations: [] ...

🤞🏻 

This PR caused https://github.com/QwenLM/Qwen3-Omni/issues/93

cc @zucchini-nlp