Run this model with HF Jobs

Run Dev9124/EKA-1-INT8 on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs and TRL to fine-tune https://huggingface.co/Dev9124/EKA-1-INT8. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/Dev9124/EKA-1-INT8 on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.

Evaluate on a benchmark

Use HF Jobs to evaluate https://huggingface.co/Dev9124/EKA-1-INT8. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
File size: 161,283 Bytes
5d293cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
# coding=utf-8
# Copyright 2023 Soket AI and The HuggingFace Inc. team. All rights reserved.
#
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
# and OPT implementations in this library. It has been modified from its
# original forms to accommodate minor architectural differences compared
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""PyTorch Eka-V1 model for HF export and inference.

Module names mirror Megatron ``MambaModel`` (``embedding``, ``decoder``,
``output_layer``, ``MambaLayer``, ``TransformerLayer``, etc.) under the
``EkaV1Model`` / ``EkaV1ForCausalLM`` wrappers. Weight paths use
``model.decoder.layers.<i>.*`` to match Megatron ``decoder.layers.<i>.*``.
"""

import math
import os
import warnings
from typing import List, Optional, Tuple, Union

import numpy as np
import torch
import torch.distributed as dist
import torch.nn.functional as F
import torch.utils.checkpoint
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from transformers.activations import ACT2FN
from transformers.cache_utils import Cache, DynamicCache

# Transformers >=5.10 split the per-layer cache into typed classes; older builds
# (e.g. the NeMo 26.02 container) still use the monolithic ``DynamicCache`` with
# no ``CacheLayerMixin`` / ``DynamicLayer`` / ``LinearAttentionLayer``.  Provide
# thin stubs so the rest of this file works on both.
try:
    from transformers.cache_utils import CacheLayerMixin, DynamicLayer, LinearAttentionLayer
except ImportError:
    # --- Minimal stubs for transformers <5.10 ---
    # CacheLayerMixin: used only in isinstance() checks to tell KV-attention slots
    #   apart from Mamba/MoE slots. The old DynamicCache has no per-layer objects at
    #   all, so nothing will ever be an instance of this stub — which is the correct
    #   answer ("no typed attention layers found → fall through to legacy path").
    class CacheLayerMixin:  # type: ignore[no-redef]
        """Stub: transformers <5.10 has no typed cache layers."""
        pass

    class DynamicLayer(CacheLayerMixin):  # type: ignore[no-redef]
        """Stub: growing key/value cache slot (transformers <5.10 fallback)."""
        def __init__(self):
            self.keys = None
            self.values = None

        def get_seq_length(self) -> int:
            if self.keys is None:
                return 0
            return self.keys.shape[-2]

        def update(self, key_states, value_states, *args, **kwargs):
            import torch
            if self.keys is None:
                self.keys = key_states
                self.values = value_states
            else:
                self.keys = torch.cat([self.keys, key_states], dim=-2)
                self.values = torch.cat([self.values, value_states], dim=-2)
            return self.keys, self.values

        def reorder_cache(self, beam_idx):
            if self.keys is not None:
                device = self.keys.device
                self.keys = self.keys.index_select(0, beam_idx.to(device))
                self.values = self.values.index_select(0, beam_idx.to(device))

        def reset(self):
            self.keys = None
            self.values = None

        def crop(self, max_length: int) -> None:
            """Truncate cached KV to ``max_length`` tokens (negative = drop that many)."""
            if self.keys is None:
                return
            if max_length < 0:
                max_length = self.get_seq_length() - abs(max_length)
            if max_length <= 0:
                self.reset()
                return
            if self.get_seq_length() <= max_length:
                return
            self.keys = self.keys[..., :max_length, :].contiguous()
            self.values = self.values[..., :max_length, :].contiguous()

    class _LinearAttentionCacheStub:
        """Stub: Mamba conv-window + SSM state slot (transformers <5.10 fallback)."""
        def __init__(self):
            self.conv_states = None
            self.recurrent_states = None
            self.has_previous_state = False
            self._is_conv_init = False
            self._is_rec_init = False

        def get_seq_length(self, layer_idx=0):
            return 0

        def get_max_cache_shape(self):
            return None

        @property
        def is_compileable(self):
            return False

        @property
        def is_sliding(self):
            return False

        def update_conv_state(self, conv_states, **kwargs):
            import torch
            if not self._is_conv_init:
                self.conv_states = torch.zeros_like(conv_states)
                self._is_conv_init = True
            if not self.has_previous_state:
                self.conv_states.copy_(conv_states)
                self.has_previous_state = True
            else:
                n = conv_states.shape[-1]
                k = self.conv_states.shape[-1]
                if n >= k:
                    self.conv_states.copy_(conv_states[..., -k:])
                else:
                    new = self.conv_states.roll(shifts=-n, dims=-1)
                    new[..., -n:] = conv_states
                    self.conv_states.copy_(new)
            return self.conv_states

        def update_recurrent_state(self, recurrent_states, **kwargs):
            import torch
            if not self._is_rec_init:
                self.recurrent_states = torch.zeros_like(recurrent_states)
                self._is_rec_init = True
            self.recurrent_states.copy_(recurrent_states)
            return self.recurrent_states

        def reorder_cache(self, beam_idx):
            if self._is_conv_init and self.conv_states is not None:
                self.conv_states = self.conv_states.index_select(0, beam_idx.to(self.conv_states.device))
            if self._is_rec_init and self.recurrent_states is not None:
                self.recurrent_states = self.recurrent_states.index_select(0, beam_idx.to(self.recurrent_states.device))

        def reset(self):
            if self._is_conv_init and self.conv_states is not None:
                self.conv_states.zero_()
            if self._is_rec_init and self.recurrent_states is not None:
                self.recurrent_states.zero_()
            self.has_previous_state = False

    LinearAttentionLayer = _LinearAttentionCacheStub  # type: ignore[misc,assignment]
from transformers.generation import GenerationMixin
from transformers.modeling_attn_mask_utils import (
    AttentionMaskConverter,
    _prepare_4d_attention_mask,
    _prepare_4d_causal_attention_mask,
)
from transformers.modeling_outputs import (
    BaseModelOutputWithPast,
    CausalLMOutputWithPast,
    SequenceClassifierOutputWithPast,
)
from transformers.modeling_utils import PreTrainedModel
from transformers.pytorch_utils import (
    ALL_LAYERNORM_LAYERS,
    is_torch_greater_or_equal_than_1_13,
)
from transformers.utils import (
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    is_flash_attn_2_available,
    is_flash_attn_greater_or_equal_2_10,
    logging,
    replace_return_docstrings,
)

try:
    from transformers.utils.import_utils import is_torch_fx_available
except ImportError:
    def is_torch_fx_available() -> bool:
        return False

from .configuration_eka import EkaV1Config

if is_flash_attn_2_available():
    from flash_attn import flash_attn_func, flash_attn_varlen_func
    from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input  # noqa

try:
    from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
except ImportError:
    causal_conv1d_fn = None
    causal_conv1d_update = None

try:
    from mamba_ssm.ops.triton.selective_state_update import selective_state_update
except ImportError:
    selective_state_update = None

try:
    from mamba_ssm.ops.triton.ssd_combined import (
        mamba_chunk_scan_combined,
        mamba_split_conv1d_scan_combined,
    )
except ImportError:
    mamba_chunk_scan_combined = None
    mamba_split_conv1d_scan_combined = None

# Megatron ``ExtendedRMSNorm`` subclasses this Triton op when mamba_ssm is present.
try:
    from mamba_ssm.ops.triton.layernorm_gated import rmsnorm_fn as _mamba_rmsnorm_fn
except ImportError:
    _mamba_rmsnorm_fn = None


# This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
# It means that the function will not be traced through and simply appear as a node in the graph.
if is_torch_fx_available():
    if not is_torch_greater_or_equal_than_1_13:
        import torch.fx

    _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)


logger = logging.get_logger(__name__)

_CONFIG_FOR_DOC = "EkaV1Config"


def _attention_layer_indices(past_key_values: Cache) -> List[int]:
    """Indices of the KV-holding slots of a hybrid cache (Mamba/MoE slots hold no KV)."""
    layers = getattr(past_key_values, "layers", None) or []
    return [idx for idx, layer in enumerate(layers) if isinstance(layer, CacheLayerMixin)]


def _cache_seq_length(past_key_values: Optional[Cache], layer_idx: Optional[int] = None) -> int:
    """Cached attention length, tolerant of the hybrid (Mamba + MLA) cache layout.

    Mamba and MoE slots are ``LinearAttentionLayer``s that track no sequence length, so
    ``Cache.get_seq_length`` raises when handed their index. Resolve to a real attention
    slot instead, and report 0 for a cache that holds no attention slot at all.
    """
    if past_key_values is None:
        return 0

    attention_indices = _attention_layer_indices(past_key_values)
    if attention_indices:
        if layer_idx is None or layer_idx not in attention_indices:
            layer_idx = attention_indices[0]
    elif getattr(past_key_values, "layers", None):
        # Mamba-only stack: nothing tracks a KV length.
        return 0
    else:
        # Lazily-built cache with no layers yet.
        return 0

    return past_key_values.get_seq_length(layer_idx)


def _eka_cache_slot_is_stateful_attention(config: EkaV1Config, layer_idx: int) -> bool:
    """Whether the decoder layer at ``layer_idx`` stores growing key/value tensors."""
    return _resolve_hybrid_layer_kind(config, layer_idx) not in ("mamba", "moe_only")


def build_eka_cache(config: EkaV1Config) -> Cache:
    """Build a cache with one slot per decoder layer, matching the hybrid pattern.

    MLA slots get a growing-KV ``DynamicLayer``; Mamba slots get a
    ``LinearAttentionLayer`` that holds the conv window plus the SSM recurrent state.
    MoE-only slots are stateless but still get a placeholder so that the ``layer_idx``
    each layer passes to ``Cache.update*`` stays aligned with the decoder stack.

    Built from ``_resolve_hybrid_layer_kind`` (the same resolver ``_build_decoder_layer``
    uses) rather than from ``config.layer_types``, so the cache layout cannot drift from
    the module layout.
    """
    layers = [
        DynamicLayer() if _eka_cache_slot_is_stateful_attention(config, layer_idx) else LinearAttentionLayer()
        for layer_idx in range(config.num_hidden_layers)
    ]
    # Transformers >=5.10 ``Cache(layers=...)`` vs older ``DynamicCache()`` that has no
    # typed-layer constructor. Fall back to monkey-patching ``.layers`` on a DynamicCache.
    try:
        cache = Cache(layers=layers)
    except TypeError:
        cache = DynamicCache()
        cache.layers = layers

        # Older DynamicCache lacks the Mamba-state delegation methods that
        # ``MambaMixer`` calls through the cache object. Wire them up here.
        def _update_conv_state(conv_states, layer_idx, **kw):
            return cache.layers[layer_idx].update_conv_state(conv_states, **kw)

        def _update_recurrent_state(recurrent_states, layer_idx, **kw):
            return cache.layers[layer_idx].update_recurrent_state(recurrent_states, **kw)

        def _has_previous_state(layer_idx):
            if layer_idx >= len(cache.layers):
                return False
            layer = cache.layers[layer_idx]
            return getattr(layer, "has_previous_state", False)

        def _get_seq_length(layer_idx=0):
            # Walk to the first KV-holding slot.
            for i, layer in enumerate(cache.layers):
                if isinstance(layer, DynamicLayer) and hasattr(layer, "get_seq_length"):
                    if layer_idx == 0 or i == layer_idx:
                        return layer.get_seq_length()
            return 0

        def _update(key_states, value_states, layer_idx, *args, **kw):
            while len(cache.layers) <= layer_idx:
                cache.layers.append(DynamicLayer())
            return cache.layers[layer_idx].update(key_states, value_states, *args, **kw)

        def _reorder(beam_idx):
            for layer in cache.layers:
                if hasattr(layer, "reorder_cache"):
                    layer.reorder_cache(beam_idx)

        cache.update = _update
        cache.update_conv_state = _update_conv_state
        cache.update_recurrent_state = _update_recurrent_state
        cache.has_previous_state = _has_previous_state
        cache.get_seq_length = _get_seq_length
        cache.reorder_cache = _reorder

    return cache


def _mtp_num_layers_from_config(config: EkaV1Config) -> int:
    return int(
        getattr(config, "mtp_num_layers", None)
        or getattr(config, "num_nextn_predict_layers", 0)
        or 0
    )


def build_mtp_cache(config: EkaV1Config) -> Cache:
    """KV cache for MTP transformer depths only (all ``DynamicLayer`` slots).

    Kept separate from the hybrid trunk cache so MTP ``layer_idx`` values stay in
    ``0 .. mtp_num_layers-1`` and rejection can rewind MTP state without touching Mamba.
    """
    num_layers = _mtp_num_layers_from_config(config)
    if num_layers <= 0:
        raise ValueError("build_mtp_cache requires mtp_num_layers > 0")
    layers = [DynamicLayer() for _ in range(num_layers)]
    try:
        return Cache(layers=layers)
    except TypeError:
        cache = DynamicCache()
        cache.layers = layers

        def _update(key_states, value_states, layer_idx, *args, **kw):
            while len(cache.layers) <= layer_idx:
                cache.layers.append(DynamicLayer())
            return cache.layers[layer_idx].update(key_states, value_states, *args, **kw)

        def _get_seq_length(layer_idx=0):
            if layer_idx < len(cache.layers) and hasattr(cache.layers[layer_idx], "get_seq_length"):
                return cache.layers[layer_idx].get_seq_length()
            return 0

        cache.update = _update
        cache.get_seq_length = _get_seq_length
        return cache


def _mtp_cache_lengths(mtp_cache: Optional[Cache]) -> List[int]:
    if mtp_cache is None or not getattr(mtp_cache, "layers", None):
        return []
    lengths = []
    for layer in mtp_cache.layers:
        if hasattr(layer, "get_seq_length"):
            lengths.append(int(layer.get_seq_length()))
        elif getattr(layer, "keys", None) is not None:
            lengths.append(int(layer.keys.shape[-2]))
        else:
            lengths.append(0)
    return lengths


def _rewind_mtp_cache(mtp_cache: Cache, target_lengths: List[int]) -> None:
    """Crop each MTP slot back to ``target_lengths[i]`` after a rejected draft suffix.

    Note: transformers ``DynamicLayer.reset()`` only zero-fills tensors and keeps the
    sequence length, so rejection must use ``crop`` (or an explicit empty slice).
    """
    for layer_idx, target in enumerate(target_lengths):
        if layer_idx >= len(mtp_cache.layers):
            break
        layer = mtp_cache.layers[layer_idx]
        cur = (
            int(layer.get_seq_length())
            if hasattr(layer, "get_seq_length")
            else (0 if getattr(layer, "keys", None) is None else int(layer.keys.shape[-2]))
        )
        target = max(0, int(target))
        if target >= cur:
            continue
        if hasattr(layer, "crop"):
            layer.crop(target)
        elif target == 0:
            layer.keys = None
            layer.values = None
        else:
            layer.keys = layer.keys[..., :target, :].contiguous()
            layer.values = layer.values[..., :target, :].contiguous()


def _get_unpad_data(attention_mask):
    seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
    indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
    max_seqlen_in_batch = seqlens_in_batch.max().item()
    cu_seqlens = F.pad(
        torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
    )
    return (
        indices,
        cu_seqlens,
        max_seqlen_in_batch,
    )


def _eka_prepare_attention_mask(
    config: EkaV1Config,
    attention_mask: Optional[torch.Tensor],
    batch_size: int,
    seq_length: int,
    hidden_states: torch.Tensor,
    past_key_values_length: int = 0,
) -> Optional[torch.Tensor]:
    """Match ``EkaV1Model`` mask handling for MTP inner blocks."""
    if config._attn_implementation == "flash_attention_2":
        if attention_mask is not None and 0 in attention_mask:
            return attention_mask
        return None
    return _prepare_4d_causal_attention_mask(
        attention_mask,
        (batch_size, seq_length),
        hidden_states,
        past_key_values_length,
    )


class RMSNorm(nn.Module):
    def __init__(self, hidden_size, eps=1e-6):
        """
        Megatron ``RMSNorm`` (equivalent to T5LayerNorm).
        """
        super().__init__()
        self.weight = nn.Parameter(torch.ones(hidden_size))
        self.variance_epsilon = eps

    def forward(self, hidden_states):
        input_dtype = hidden_states.dtype
        hidden_states = hidden_states.to(torch.float32)
        variance = hidden_states.pow(2).mean(-1, keepdim=True)
        hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
        # Match Megatron/TE: scale in fp32, then cast (bf16 weight*bf16-cast loses ULP).
        return (self.weight.float() * hidden_states).to(input_dtype)


ALL_LAYERNORM_LAYERS.append(RMSNorm)


class IdentityOp(nn.Module):
    """Megatron no-op submodule (e.g. unused cross-attn on decoder layers)."""

    def forward(self, hidden_states, *args, **kwargs):
        if args or kwargs:
            return hidden_states, None, None
        return hidden_states


class LanguageModelEmbedding(nn.Module):
    """Megatron ``LanguageModelEmbedding`` (``word_embeddings`` + dropout)."""

    def __init__(self, config: EkaV1Config):
        super().__init__()
        self.word_embeddings = nn.Embedding(
            config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id
        )
        dropout_p = getattr(config, "hidden_dropout", 0.0) or 0.0
        self.embedding_dropout = nn.Dropout(p=dropout_p)

    def forward(self, input_ids: torch.LongTensor) -> torch.Tensor:
        return self.embedding_dropout(self.word_embeddings(input_ids))


def _eka_debug_mlp_enabled() -> bool:
    """Step-level MoE/MLP I/O dumps when ``EKA_DEBUG_MLP=1`` (parity / diagnosis)."""
    return os.environ.get("EKA_DEBUG_MLP", "").strip().lower() in ("1", "true", "yes")


def _eka_debug_mlp_max_experts() -> int:
    try:
        return max(0, int(os.environ.get("EKA_DEBUG_MLP_MAX_EXPERTS", "4")))
    except ValueError:
        return 4


def _eka_log_tensor(tag: str, t: Optional[torch.Tensor], extra: str = "") -> None:
    """Compact tensor stats for MoE/MLP parity debugging (rank-0 only if distributed)."""
    if not _eka_debug_mlp_enabled():
        return
    if dist.is_available() and dist.is_initialized() and dist.get_rank() != 0:
        return
    if t is None:
        print(f"[eka-mlp-debug] {tag}: None {extra}", flush=True)
        return
    with torch.no_grad():
        flat = t.detach().float().reshape(-1)
        n = min(8, flat.numel())
        sample = flat[:n].tolist() if n else []
        msg = (
            f"[eka-mlp-debug] {tag}: shape={tuple(t.shape)} dtype={t.dtype} "
            f"mean={flat.mean().item():.6g} absmax={flat.abs().max().item():.6g} "
            f"sample={sample}"
        )
        if extra:
            msg = f"{msg} {extra}"
        print(msg, flush=True)



class EkaQuantLinear(nn.Module):
    """Weight-only INT8 / INT4 linear used by the quantized EKA-1 checkpoints.

    Weights are stored packed (``weight_q``) with per-row (INT8) or per-group
    (INT4, symmetric, group_size) scales in ``weight_scale`` and are
    dequantized lazily on first use (weights are static at inference).
    Enabled by ``config.quantization_config = {"quant_method": "eka-quant"}``.
    """

    def __init__(self, in_features, out_features, bias=False, bits=8, group_size=64):
        super().__init__()
        self.in_features = in_features
        self.out_features = out_features
        self.bits = bits
        self.group_size = group_size
        if bits == 8:
            self.register_buffer(
                "weight_q", torch.empty(out_features, in_features, dtype=torch.int8)
            )
            self.register_buffer(
                "weight_scale", torch.empty(out_features, 1, dtype=torch.bfloat16)
            )
        elif bits == 4:
            if in_features % group_size:
                raise ValueError(f"in_features={in_features} not divisible by {group_size}")
            self.register_buffer(
                "weight_q", torch.empty(out_features, in_features // 2, dtype=torch.uint8)
            )
            self.register_buffer(
                "weight_scale",
                torch.empty(out_features, in_features // group_size, dtype=torch.bfloat16),
            )
        else:
            raise ValueError(f"unsupported bits={bits}")
        self.bias = nn.Parameter(torch.zeros(out_features)) if bias else None
        self._deq_cache = None

    def dequantize(self):
        if self.bits == 8:
            w = self.weight_q.to(torch.float32) * self.weight_scale.to(torch.float32)
            return w.to(torch.bfloat16)
        q = self.weight_q
        lo = (q & 0x0F).to(torch.float32) - 8.0
        hi = (q >> 4).to(torch.float32) - 8.0
        w = torch.stack((lo, hi), dim=-1).reshape(q.shape[0], -1)
        w = w.view(q.shape[0], -1, self.group_size)
        w = w * self.weight_scale.to(torch.float32).unsqueeze(-1)
        return w.reshape(q.shape[0], -1).to(torch.bfloat16)

    def forward(self, x):
        w = self._deq_cache
        if w is None or w.device != x.device:
            w = self.dequantize().to(x.device)
            self._deq_cache = w
        return F.linear(x, w.to(x.dtype), self.bias)


def _eka_quant_skip(name: str) -> bool:
    return (
        name.endswith(".gate")
        or name == "gate"
        or "output_layer" in name
        or "lm_head" in name
        or "embedding" in name
    )


@torch.no_grad()
def _eka_make_quant_linear(lin: nn.Linear, bits: int, group_size: int) -> EkaQuantLinear:
    w = lin.weight.detach().float()
    out_f, in_f = w.shape
    q = EkaQuantLinear(in_f, out_f, lin.bias is not None, bits, group_size).to(w.device)
    if bits == 8:
        scale = (w.abs().amax(dim=1, keepdim=True).clamp_min(1e-8) / 127.0).to(torch.float32)
        q.weight_q.copy_(torch.round(w / scale).clamp_(-127, 127).to(torch.int8))
        q.weight_scale.copy_(scale.to(torch.bfloat16))
    else:
        g = in_f // group_size
        wr = w.view(out_f, g, group_size)
        scale = wr.abs().amax(dim=-1, keepdim=True).clamp_min(1e-8) / 7.0
        qq = (torch.round(wr / scale).clamp_(-8, 7).to(torch.int8) + 8).to(torch.uint8)
        qq = qq.view(out_f, in_f)
        q.weight_q.copy_((qq[:, 0::2] | (qq[:, 1::2] << 4)).to(torch.uint8))
        q.weight_scale.copy_(scale.squeeze(-1).to(torch.bfloat16))
    if lin.bias is not None:
        q.bias.copy_(lin.bias.data)
    return q


@torch.no_grad()
def replace_linear_with_quant(module: nn.Module, bits: int, group_size: int = 64, _prefix: str = ""):
    """Replace every eligible nn.Linear with an EkaQuantLinear (quantizing its weight)."""
    for name, child in list(module.named_children()):
        full = f"{_prefix}.{name}" if _prefix else name
        if isinstance(child, nn.Linear):
            if _eka_quant_skip(full):
                continue
            if child.weight.shape[1] % group_size and bits == 4:
                continue
            setattr(module, name, _eka_make_quant_linear(child, bits, group_size))
        else:
            replace_linear_with_quant(child, bits, group_size, full)


class LinearFC1(nn.Module):
    """Megatron gated ``linear_fc1`` (SiLU-gate × up).

    Checkpoint keeps split ``gate_proj`` / ``up_proj`` (export from fused Megatron
    ``linear_fc1`` / TE GroupedGEMM). Forward concatenates weights into **one** GEMM
    then ``silu(gate)*up`` — same algebra as Megatron ``bias_swiglu`` /
    ``weighted_bias_swiglu`` (job 315506: two separate GEMMs were bit-identical on
    that input, but the fused path is the Megatron-aligned default).
    """

    def __init__(self, in_features: int, out_features: int, bias: bool = False):
        super().__init__()
        self.gate_proj = nn.Linear(in_features, out_features, bias=bias)
        self.up_proj = nn.Linear(in_features, out_features, bias=bias)

    def forward(self, x: torch.Tensor, act_fn) -> torch.Tensor:
        _eka_log_tensor("LinearFC1.in", x)
        if isinstance(self.gate_proj, EkaQuantLinear):
            # Quantized path: two projections, concatenated outputs.
            gate_up = torch.cat([self.gate_proj(x), self.up_proj(x)], dim=-1)
        else:
            # Fused fc1 = cat(gate, up) — mirrors Megatron chunk(linear_fc1(x), 2).
            weight = torch.cat(
                [self.gate_proj.weight, self.up_proj.weight], dim=0
            ).contiguous()
            bias = None
            if self.gate_proj.bias is not None or self.up_proj.bias is not None:
                bias = torch.cat(
                    [
                        self.gate_proj.bias
                        if self.gate_proj.bias is not None
                        else x.new_zeros(self.gate_proj.out_features),
                        self.up_proj.bias
                        if self.up_proj.bias is not None
                        else x.new_zeros(self.up_proj.out_features),
                    ],
                    dim=0,
                )
            gate_up = F.linear(x, weight, bias)
        gate, up = gate_up.chunk(2, dim=-1)
        _eka_log_tensor("LinearFC1.gate", gate)
        _eka_log_tensor("LinearFC1.up", up)
        out = act_fn(gate) * up
        _eka_log_tensor("LinearFC1.out(swiglu_fused)", out)
        if _eka_debug_mlp_enabled():
            # Optional: quantify vs two separate GEMMs (does not change return).
            gate2 = self.gate_proj(x)
            up2 = self.up_proj(x)
            out_two = act_fn(gate2) * up2
            diff = (out.float() - out_two.float()).abs()
            _eka_log_tensor("LinearFC1.out(swiglu_two_gemm)", out_two)
            _eka_log_tensor(
                "LinearFC1.diff(fused_vs_two_gemm)",
                diff,
                extra=f"rel={(diff.mean() / (out.float().abs().mean() + 1e-8)).item():.6g}",
            )
        return out


class RotaryEmbedding(nn.Module):
    def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
        super().__init__()

        self.dim = dim
        self.max_position_embeddings = max_position_embeddings
        self.base = base
        inv_freq = 1.0 / (
            self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
        )
        self.register_buffer("inv_freq", inv_freq, persistent=False)

        # Build here to make `torch.jit.trace` work.
        self._set_cos_sin_cache(
            seq_len=max_position_embeddings,
            device=self.inv_freq.device,
            dtype=torch.get_default_dtype(),
        )
        self.max_seq_len_cached = None

    def _set_cos_sin_cache(self, seq_len, device, dtype):
        self.max_seq_len_cached = seq_len
        t = torch.arange(
            self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
        )

        freqs = torch.outer(t, self.inv_freq.to(t.device))
        # Different from paper, but it uses a different permutation in order to obtain the same calculation
        emb = torch.cat((freqs, freqs), dim=-1)
        self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
        self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)

    def forward(self, x, seq_len=None):
        # x: [bs, num_attention_heads, seq_len, head_size]
        if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
            self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)

        return (
            self.cos_cached[:seq_len].to(dtype=x.dtype),
            self.sin_cached[:seq_len].to(dtype=x.dtype),
        )


# Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->Eka-v1
class LinearScalingRotaryEmbedding(RotaryEmbedding):
    """RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""

    def __init__(
        self,
        dim,
        max_position_embeddings=2048,
        base=10000,
        device=None,
        scaling_factor=1.0,
    ):
        self.scaling_factor = scaling_factor
        super().__init__(dim, max_position_embeddings, base, device)

    def _set_cos_sin_cache(self, seq_len, device, dtype):
        self.max_seq_len_cached = seq_len
        t = torch.arange(
            self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
        )
        t = t / self.scaling_factor

        freqs = torch.outer(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.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
        self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)

class DynamicNTKScalingRotaryEmbedding(RotaryEmbedding):
    """RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""

    def __init__(
        self,
        dim,
        max_position_embeddings=2048,
        base=10000,
        device=None,
        scaling_factor=1.0,
    ):
        self.scaling_factor = scaling_factor
        super().__init__(dim, max_position_embeddings, base, device)

    def _set_cos_sin_cache(self, seq_len, device, dtype):
        self.max_seq_len_cached = seq_len

        if seq_len > self.max_position_embeddings:
            base = self.base * (
                (self.scaling_factor * seq_len / self.max_position_embeddings)
                - (self.scaling_factor - 1)
            ) ** (self.dim / (self.dim - 2))
            inv_freq = 1.0 / (
                base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
            )
            self.register_buffer("inv_freq", inv_freq, persistent=False)

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

        freqs = torch.outer(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.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
        self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)


# Inverse dim formula to find dim based on number of rotations
def yarn_find_correction_dim(
    num_rotations, dim, base=10000, max_position_embeddings=2048
):
    return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (
        2 * math.log(base)
    )


# Find dim range bounds based on rotations
def yarn_find_correction_range(
    low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
):
    low = math.floor(
        yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)
    )
    high = math.ceil(
        yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings)
    )
    return max(low, 0), min(high, dim - 1)  # Clamp values just in case


def yarn_get_mscale(scale=1, mscale=1):
    if scale <= 1:
        return 1.0
    return 0.1 * mscale * math.log(scale) + 1.0


def yarn_linear_ramp_mask(min, max, dim):
    if min == max:
        max += 0.001  # Prevent singularity

    linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
    ramp_func = torch.clamp(linear_func, 0, 1)
    return ramp_func


class YarnRotaryEmbedding(RotaryEmbedding):
    def __init__(
        self,
        dim,
        max_position_embeddings=2048,
        base=10000,
        device=None,
        scaling_factor=1.0,
        original_max_position_embeddings=4096,
        beta_fast=32,
        beta_slow=1,
        mscale=1,
        mscale_all_dim=0,
    ):
        self.scaling_factor = scaling_factor
        self.original_max_position_embeddings = original_max_position_embeddings
        self.beta_fast = beta_fast
        self.beta_slow = beta_slow
        self.mscale = mscale
        self.mscale_all_dim = mscale_all_dim
        super().__init__(dim, max_position_embeddings, base, device)

    def _set_cos_sin_cache(self, seq_len, device, dtype):
        self.max_seq_len_cached = seq_len
        dim = self.dim

        freq_extra = 1.0 / (
            self.base
            ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
        )
        freq_inter = 1.0 / (
            self.scaling_factor
            * self.base
            ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
        )

        low, high = yarn_find_correction_range(
            self.beta_fast,
            self.beta_slow,
            dim,
            self.base,
            self.original_max_position_embeddings,
        )
        inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
            device=device, dtype=torch.float32
        )
        inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
        self.register_buffer("inv_freq", inv_freq, persistent=False)

        t = torch.arange(seq_len, device=device, dtype=torch.float32)

        freqs = torch.outer(t, inv_freq)

        _mscale = float(
            yarn_get_mscale(self.scaling_factor, self.mscale)
            / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
        )

        emb = torch.cat((freqs, freqs), dim=-1)
        self.register_buffer(
            "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False
        )
        self.register_buffer(
            "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False
        )


# Copied from transformers.models.llama.modeling_llama.rotate_half
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)


# Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
def apply_rotary_pos_emb(
    q,
    k,
    cos,
    sin,
    position_ids,
    unsqueeze_dim=1,
    rotary_interleaved: bool = False,
    multi_latent_attention: bool = False,
):
    """Applies Rotary Position Embedding to the query and key tensors.

    Megatron Eka-V1 uses ``rotary_interleaved=False`` (see ``run_config.yaml``).
    For MLA, Megatron ``rope_utils._apply_rotary_pos_emb_bshd`` first rearranges
    even/odd elements into contiguous halves before ``rotate_half`` — set
    ``multi_latent_attention=True`` to match that path.
    """
    cos = cos[position_ids].unsqueeze(unsqueeze_dim)
    sin = sin[position_ids].unsqueeze(unsqueeze_dim)

    if multi_latent_attention:
        # Megatron MLA: [e0, o0, e1, o1, ...] -> [e0, e1, ..., o0, o1, ...]
        def _mla_even_odd_to_halves(x: torch.Tensor) -> torch.Tensor:
            x1 = x[..., 0::2]
            x2 = x[..., 1::2]
            return torch.cat((x1, x2), dim=-1)

        q = _mla_even_odd_to_halves(q)
        k = _mla_even_odd_to_halves(k)
    elif rotary_interleaved:
        b, h, s, d = q.shape
        q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
        b, h, s, d = k.shape
        k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)

    q_embed = (q * cos) + (rotate_half(q) * sin)
    k_embed = (k * cos) + (rotate_half(k) * sin)
    return q_embed, k_embed


class MLP(nn.Module):
    """Dense MLP block (Megatron ``mlp.linear_fc1`` / ``linear_fc2``)."""

    def __init__(self, config, hidden_size=None, intermediate_size=None):
        super().__init__()
        self.config = config
        self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
        self.intermediate_size = (
            config.intermediate_size if intermediate_size is None else intermediate_size
        )
        self.act_fn = ACT2FN[config.hidden_act]
        self.linear_fc1 = LinearFC1(self.hidden_size, self.intermediate_size, bias=False)
        self.linear_fc2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)

    def forward(self, x, token_probs: Optional[torch.Tensor] = None):
        # Megatron ``weighted_swiglu``: swiglu(fc1(x)) * probs, then cast back to x.dtype
        # before fc2 (``bias_activation_fusion`` path in TEGroupedMLP).
        _eka_log_tensor("MLP.in", x)
        _eka_log_tensor("MLP.token_probs", token_probs)
        h = self.linear_fc1(x, self.act_fn)
        _eka_log_tensor("MLP.after_fc1_swiglu", h)
        if token_probs is not None:
            dtype = h.dtype
            # Router probs stay fp32 when moe_router_dtype=fp32; multiply promotes then cast.
            # Match TE weighted_swiglu: scale in higher precision, return activation dtype.
            h = (h.float() * token_probs.unsqueeze(-1).float()).to(dtype)
            _eka_log_tensor("MLP.after_weighted_swiglu", h)
        out = self.linear_fc2(h)
        _eka_log_tensor("MLP.out", out)
        return out


class SharedExpertMLP(MLP):
    """Megatron ``SharedExpertMLP`` (wider intermediate for shared experts).

    Uses the same fused ``LinearFC1`` + SwiGLU path as routed experts / TE; shared
    experts are never router-weighted.
    """

    def forward(self, x, token_probs: Optional[torch.Tensor] = None):
        if token_probs is not None:
            # Shared experts are never router-weighted in Megatron.
            raise ValueError("SharedExpertMLP does not take token_probs")
        _eka_log_tensor("SharedExpertMLP.in", x)
        out = super().forward(x, token_probs=None)
        _eka_log_tensor("SharedExpertMLP.out", out)
        return out

class TopKRouter(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.config = config
        self.top_k = config.num_experts_per_tok
        self.n_routed_experts = config.n_routed_experts
        self.routed_scaling_factor = config.routed_scaling_factor
        self.scoring_func = config.scoring_func
        self.topk_method = config.topk_method
        self.n_group = config.n_group
        self.topk_group = config.topk_group

        # topk selection algorithm
        self.norm_topk_prob = config.norm_topk_prob
        self.gating_dim = config.hidden_size
        self.weight = nn.Parameter(
            torch.empty((self.n_routed_experts, self.gating_dim))
        )
        # Megatron keeps expert_bias in float32; bf16 (ULP~0.25 near 38) collapses
        # per-expert deltas and completely changes top-k routing.
        if self.topk_method == "noaux_tc":
            self.register_buffer(
                "e_score_correction_bias",
                torch.zeros(self.n_routed_experts, dtype=torch.float32),
            )
        self.reset_parameters()

    @property
    def expert_bias(self):
        return self.e_score_correction_bias

    def _maintain_float32_expert_bias(self) -> None:
        """Keep routing bias in float32 after dtype casts (matches Megatron)."""
        if (
            hasattr(self, "e_score_correction_bias")
            and self.e_score_correction_bias is not None
            and self.e_score_correction_bias.dtype != torch.float32
        ):
            self.e_score_correction_bias.data = self.e_score_correction_bias.data.to(
                torch.float32
            )

    def reset_parameters(self) -> None:
        import torch.nn.init as init

        init.kaiming_uniform_(self.weight, a=math.sqrt(5))

    def forward(self, hidden_states):
        bsz, seq_len, h = hidden_states.shape
        self._maintain_float32_expert_bias()
        ### compute gating score
        hidden_states = hidden_states.view(-1, h)
        logits = F.linear(
            hidden_states.type(torch.float32), self.weight.type(torch.float32), None
        )
        if self.scoring_func == "sigmoid":
            # Megatron: sigmoid in fp32 then type_as(logits); with moe_router_dtype=fp32
            # logits stay fp32 so scores remain fp32 through gather/normalize.
            scores = torch.sigmoid(logits)
        else:
            raise NotImplementedError(
                f"insupportable scoring function for MoE gating: {self.scoring_func}"
            )

        ### select top-k experts
        if self.topk_method == "noaux_tc":
            assert not self.training
            # Bias is selection-only (Megatron sigmoid path); keep fp32 for ranking.
            scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.to(
                dtype=torch.float32
            ).unsqueeze(0)
            # Match Megatron group_limited_topk: topk(topk // group_topk) per group.
            group_inner_k = max(self.top_k // max(self.topk_group, 1), 1)
            group_scores = (
                scores_for_choice.view(bsz * seq_len, self.n_group, -1)
                .topk(group_inner_k, dim=-1)[0]
                .sum(dim=-1)
            )  # [n, n_group]
            # Megatron ``torch.topk`` defaults to sorted=True — same order for bf16 sum.
            group_idx = torch.topk(
                group_scores, k=self.topk_group, dim=-1, sorted=True
            )[1]  # [n, top_k_group]
            group_mask = torch.zeros_like(group_scores)  # [n, n_group]
            group_mask.scatter_(1, group_idx, 1)  # [n, n_group]
            score_mask = (
                group_mask.unsqueeze(-1)
                .expand(
                    bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
                )
                .reshape(bsz * seq_len, -1)
            )  # [n, e]
            tmp_scores = scores_for_choice.masked_fill(
                ~score_mask.bool(), float("-inf")
            )  # [n, e]
            _, topk_idx = torch.topk(tmp_scores, k=self.top_k, dim=-1, sorted=True)
            topk_weight = scores.gather(1, topk_idx)
        else:
            raise NotImplementedError(
                f"insupportable TopK function for MoE gating: {self.topk_method}"
            )

        ### norm gate to sum 1
        if self.top_k > 1 and self.norm_topk_prob:
            denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
            topk_weight = topk_weight / denominator
        topk_weight = (
            topk_weight * self.routed_scaling_factor
        )  # must multiply the scaling factor

        if _eka_debug_mlp_enabled():
            _eka_log_tensor("TopKRouter.logits", logits)
            _eka_log_tensor("TopKRouter.scores", scores)
            _eka_log_tensor("TopKRouter.topk_idx", topk_idx)
            _eka_log_tensor("TopKRouter.topk_weight", topk_weight)
            if dist.is_available() and dist.is_initialized() and dist.get_rank() != 0:
                pass
            else:
                print(
                    f"[eka-mlp-debug] TopKRouter.topk_idx[0]={topk_idx[0].tolist()} "
                    f"topk_weight[0]={topk_weight[0].detach().float().tolist()}",
                    flush=True,
                )

        return topk_idx, topk_weight


class MoELayer(nn.Module):
    """Megatron ``MoELayer`` (router + latent proj + experts + shared experts)."""

    def __init__(self, config):
        super().__init__()
        self.config = config
        self.num_experts_per_tok = config.num_experts_per_tok
        self.moe_latent_size = getattr(config, "moe_latent_size", None)

        if self.moe_latent_size:
            self.fc1_latent_proj = nn.Linear(config.hidden_size, self.moe_latent_size, bias=False)
            self.fc2_latent_proj = nn.Linear(self.moe_latent_size, config.hidden_size, bias=False)
            # Megatron ``TENorm`` on latent dim (pre-dispatch / pre-up-proj).
            self.fc1_latent_norm = RMSNorm(self.moe_latent_size, eps=config.rms_norm_eps)
            self.fc2_latent_norm = RMSNorm(self.moe_latent_size, eps=config.rms_norm_eps)
            expert_hidden = self.moe_latent_size
        else:
            expert_hidden = config.hidden_size

        if hasattr(config, "ep_size") and config.ep_size > 1:
            assert config.ep_size == dist.get_world_size()
            self.ep_size = config.ep_size
            self.experts_per_rank = config.n_routed_experts // config.ep_size
            self.ep_rank = dist.get_rank()
            self.experts = nn.ModuleList(
                [
                    (
                        MLP(
                            config,
                            hidden_size=expert_hidden,
                            intermediate_size=config.moe_intermediate_size,
                        )
                        if i >= self.ep_rank * self.experts_per_rank
                        and i < (self.ep_rank + 1) * self.experts_per_rank
                        else None
                    )
                    for i in range(config.n_routed_experts)
                ]
            )
        else:
            self.ep_size = 1
            self.experts_per_rank = config.n_routed_experts
            self.ep_rank = 0
            self.experts = nn.ModuleList(
                [
                    MLP(
                        config,
                        hidden_size=expert_hidden,
                        intermediate_size=config.moe_intermediate_size,
                    )
                    for i in range(config.n_routed_experts)
                ]
            )
        self.router = TopKRouter(config)
        if config.n_shared_experts is not None:
            intermediate_size = config.moe_intermediate_size * config.n_shared_experts
            self.shared_experts = SharedExpertMLP(
                config=config, intermediate_size=intermediate_size
            )

    def forward(self, hidden_states):
        identity = hidden_states
        orig_shape = hidden_states.shape
        out_dtype = hidden_states.dtype
        _eka_log_tensor("MoELayer.in", hidden_states)
        topk_idx, topk_weight = self.router(hidden_states)
        routed = hidden_states
        if self.moe_latent_size:
            routed = self.fc1_latent_proj(routed)
            _eka_log_tensor("MoELayer.after_fc1_latent_proj", routed)
            routed = self.fc1_latent_norm(routed)
            _eka_log_tensor("MoELayer.after_fc1_latent_norm", routed)
        hidden_states = routed.view(-1, routed.shape[-1])
        y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape[:-1], -1)
        _eka_log_tensor("MoELayer.after_routed_experts", y)
        if self.moe_latent_size:
            y = self.fc2_latent_norm(y)
            _eka_log_tensor("MoELayer.after_fc2_latent_norm", y)
            y = self.fc2_latent_proj(y)
            _eka_log_tensor("MoELayer.after_fc2_latent_proj", y)
        if self.config.n_shared_experts is not None:
            # Megatron postprocess: add shared expert on the pre-latent identity.
            # fp32 add reduces bf16 ULP noise when combining large routed + shared outs.
            shared = self.shared_experts(identity)
            _eka_log_tensor("MoELayer.shared_experts_out", shared)
            y = (y.float() + shared.float()).to(out_dtype)
        _eka_log_tensor("MoELayer.out", y)
        return y

    @torch.no_grad()
    def moe_infer(self, x, topk_ids, topk_weight):
        """Permute tokens by expert id, run experts, unpermute and sum top-k slots.

        Matches the HF path that best tracked Megatron EP=8 TEGroupedMLP on full
        ``MoETransformerLayer`` parity (job 315452: max_abs=8, mean_abs≈0.97).
        Router probs are applied inside each expert before fc2 (``weighted_swiglu``).
        """
        _eka_log_tensor("moe_infer.in", x)
        cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
        cnts.scatter_(1, topk_ids, 1)
        tokens_per_expert = cnts.sum(dim=0)
        idxs = topk_ids.view(-1).argsort()
        sorted_tokens = x[idxs // topk_ids.shape[1]]
        permuted_probs = topk_weight.view(-1)[idxs]
        sorted_tokens_shape = sorted_tokens.shape
        _eka_log_tensor("moe_infer.sorted_tokens", sorted_tokens)
        _eka_log_tensor("moe_infer.permuted_probs", permuted_probs)
        if _eka_debug_mlp_enabled() and (
            not dist.is_available()
            or not dist.is_initialized()
            or dist.get_rank() == 0
        ):
            nz = (tokens_per_expert > 0).nonzero(as_tuple=False).view(-1)[:16].tolist()
            print(
                f"[eka-mlp-debug] moe_infer.tokens_per_expert nonzero[:16]={nz} "
                f"counts={[int(tokens_per_expert[i]) for i in nz]}",
                flush=True,
            )

        if self.ep_size > 1:
            tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1)
            tokens_per_expert_group = tokens_per_expert.new_empty(
                tokens_per_expert.shape[0]
            )
            dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
            output_splits = (
                tokens_per_expert_group.view(self.ep_size, -1)
                .sum(1)
                .cpu()
                .numpy()
                .tolist()
            )
            gathered_tokens = sorted_tokens.new_empty(
                int(tokens_per_expert_group.sum().item()), sorted_tokens.shape[1]
            )
            input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
            dist.all_to_all(
                list(gathered_tokens.split(output_splits)),
                list(sorted_tokens.split(input_split_sizes)),
            )
            tokens_per_expert_post_gather = tokens_per_expert_group.view(
                self.ep_size, self.experts_per_rank
            ).sum(dim=0)
            gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32)
            s = 0
            for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
                gatherd_idxs[s : s + k] = i % self.experts_per_rank
                s += k
            gatherd_idxs = gatherd_idxs.argsort()
            sorted_tokens = gathered_tokens[gatherd_idxs]
            permuted_probs = permuted_probs[gatherd_idxs]
            tokens_per_expert = tokens_per_expert_post_gather
            _eka_log_tensor("moe_infer.after_ep_gather.sorted_tokens", sorted_tokens)

        tokens_per_expert_list = tokens_per_expert.cpu().tolist()
        outputs = []
        start_idx = 0
        logged_experts = 0
        max_experts_log = _eka_debug_mlp_max_experts()
        for i, num_tok in enumerate(tokens_per_expert_list):
            num_tok = int(num_tok)
            end_idx = start_idx + num_tok
            if num_tok == 0:
                continue
            expert_id = i + self.ep_rank * self.experts_per_rank
            expert = self.experts[expert_id]
            if logged_experts < max_experts_log:
                _eka_log_tensor(
                    f"moe_infer.expert[{expert_id}].in",
                    sorted_tokens[start_idx:end_idx],
                    extra=f"n_tok={num_tok}",
                )
                _eka_log_tensor(
                    f"moe_infer.expert[{expert_id}].probs",
                    permuted_probs[start_idx:end_idx],
                )
            expert_out = expert(
                sorted_tokens[start_idx:end_idx],
                token_probs=permuted_probs[start_idx:end_idx],
            )
            if logged_experts < max_experts_log:
                _eka_log_tensor(f"moe_infer.expert[{expert_id}].out", expert_out)
                logged_experts += 1
            outputs.append(expert_out)
            start_idx = end_idx

        outs = (
            torch.cat(outputs, dim=0)
            if len(outputs)
            else sorted_tokens.new_empty(0, x.shape[-1])
        )
        _eka_log_tensor("moe_infer.cat_expert_outs", outs)
        if self.ep_size > 1:
            new_x = torch.empty_like(outs)
            new_x[gatherd_idxs] = outs
            gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
            dist.all_to_all(
                list(gathered_tokens.split(input_split_sizes)),
                list(new_x.split(output_splits)),
            )
            outs = gathered_tokens

        new_x = torch.empty_like(outs)
        new_x[idxs] = outs
        # Probs already applied inside experts; sum the top-k slots.
        # fp32 reduce matches numerical stability of combining many large expert outs
        # (Megatron TEGroupedMLP combine) better than summing in bf16 alone.
        final_out = new_x.view(*topk_ids.shape, -1).float().sum(dim=1).to(x.dtype)
        _eka_log_tensor("moe_infer.out", final_out)
        return final_out


def _vrs_subtract_projection(y: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
    """Value Residual Subtraction: z = y - proj_v(y), orthogonalizing attn output to value."""
    dot = (y * v).sum(dim=-1, keepdim=True)
    v_sq = (v * v).sum(dim=-1, keepdim=True).clamp(min=1e-8)
    return y - (dot / v_sq) * v


def _maybe_apply_vrs(
    config: EkaV1Config,
    attn_output: torch.Tensor,
    value_states: torch.Tensor,
    v_head_dim: int,
) -> torch.Tensor:
    """Optional VRS; no-op when ``value_residual_subtraction`` is False (default / MLASelfAttention)."""
    if not getattr(config, "value_residual_subtraction", False):
        return attn_output
    y = attn_output[..., :v_head_dim]
    v = value_states[..., :v_head_dim]
    if y.shape != v.shape:
        # Match Megatron: trim value along the sequence axis if lengths differ (decode edge cases).
        for dim in range(y.dim()):
            if y.shape[dim] != v.shape[dim]:
                min_len = min(y.shape[dim], v.shape[dim])
                y = y.narrow(dim, 0, min_len)
                v = v.narrow(dim, 0, min_len)
                break
    z = _vrs_subtract_projection(y, v)
    if attn_output.shape[-1] == v_head_dim:
        return z
    out = attn_output.clone()
    out[..., :v_head_dim] = z
    return out


# Copied from transformers.models.llama.modeling_llama.repeat_kv
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
    """
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    """
    batch, num_key_value_heads, slen, head_dim = hidden_states.shape
    if n_rep == 1:
        return hidden_states
    hidden_states = hidden_states[:, :, None, :, :].expand(
        batch, num_key_value_heads, n_rep, slen, head_dim
    )
    return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)


# Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->Eka-v1
class MLASelfAttention(nn.Module):
    """Megatron ``MLASelfAttention`` (``self_attention``).

    Yarn/RoPE is applied **inside** this module (same as Megatron MLA). Callers must
    not inject external ``rotary_pos_emb`` — Megatron asserts that argument is None.

    Matches training when ``value_residual_subtraction=False`` (default).
    If that flag is True, optionally applies VRS on the attention output.
    """

    def __init__(self, config: EkaV1Config, layer_idx: Optional[int] = None):
        super().__init__()
        self.config = config
        self.layer_idx = layer_idx
        if layer_idx is None:
            logger.warning_once(
                f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
                "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
                "when creating this class."
            )

        self.attention_dropout = config.attention_dropout
        self.hidden_size = config.hidden_size
        self.num_heads = config.num_attention_heads

        self.max_position_embeddings = config.max_position_embeddings
        self.rope_theta = config.rope_theta
        self.q_lora_rank = config.q_lora_rank
        self.qk_rope_head_dim = config.qk_rope_head_dim
        self.kv_lora_rank = config.kv_lora_rank
        self.v_head_dim = config.v_head_dim
        self.qk_nope_head_dim = config.qk_nope_head_dim
        self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim

        self.is_causal = True

        if self.q_lora_rank is None:
            self.linear_q_proj = nn.Linear(
                self.hidden_size, self.num_heads * self.q_head_dim, bias=False
            )
        else:
            self.linear_q_down_proj = nn.Linear(
                self.hidden_size, config.q_lora_rank, bias=config.attention_bias
            )
            self.q_layernorm = RMSNorm(config.q_lora_rank)
            self.linear_q_up_proj = nn.Linear(
                config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
            )

        self.linear_kv_down_proj = nn.Linear(
            self.hidden_size,
            config.kv_lora_rank + config.qk_rope_head_dim,
            bias=config.attention_bias,
        )
        self.kv_layernorm = RMSNorm(config.kv_lora_rank)
        self.linear_kv_up_proj = nn.Linear(
            config.kv_lora_rank,
            self.num_heads
            * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
            bias=False,
        )

        self.linear_proj = nn.Linear(
            self.num_heads * self.v_head_dim,
            self.hidden_size,
            bias=config.attention_bias,
        )
        self._init_rope()

        self.softmax_scale = self.q_head_dim ** (-0.5)
        if self.config.rope_scaling is not None:
            mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
            scaling_factor = self.config.rope_scaling["factor"]
            if mscale_all_dim:
                mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
                self.softmax_scale = self.softmax_scale * mscale * mscale

    def _init_rope(self):
        if self.config.rope_scaling is None:
            self.rotary_pos_emb = RotaryEmbedding(
                self.qk_rope_head_dim,
                max_position_embeddings=self.max_position_embeddings,
                base=self.rope_theta,
            )
        else:
            scaling_type = self.config.rope_scaling["type"]
            scaling_factor = self.config.rope_scaling["factor"]
            if scaling_type == "linear":
                self.rotary_pos_emb = LinearScalingRotaryEmbedding(
                    self.qk_rope_head_dim,
                    max_position_embeddings=self.max_position_embeddings,
                    scaling_factor=scaling_factor,
                    base=self.rope_theta,
                )
            elif scaling_type == "dynamic":
                self.rotary_pos_emb = DynamicNTKScalingRotaryEmbedding(
                    self.qk_rope_head_dim,
                    max_position_embeddings=self.max_position_embeddings,
                    scaling_factor=scaling_factor,
                    base=self.rope_theta,
                )
            elif scaling_type == "yarn":
                kwargs = {
                    key: self.config.rope_scaling[key]
                    for key in [
                        "original_max_position_embeddings",
                        "beta_fast",
                        "beta_slow",
                        "mscale",
                        "mscale_all_dim",
                    ]
                    if key in self.config.rope_scaling
                }
                self.rotary_pos_emb = YarnRotaryEmbedding(
                    self.qk_rope_head_dim,
                    max_position_embeddings=self.max_position_embeddings,
                    scaling_factor=scaling_factor,
                    base=self.rope_theta,
                    **kwargs,
                )
            else:
                raise ValueError(f"Unknown RoPE scaling type {scaling_type}")

    def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
        return (
            tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
            .transpose(1, 2)
            .contiguous()
        )

    def _default_position_ids(
        self,
        hidden_states: torch.Tensor,
        past_key_value: Optional[Cache],
        q_len: int,
    ) -> torch.LongTensor:
        """Megatron MLA derives positions from the sequence; offset by any cached prefix."""
        past_length = _cache_seq_length(past_key_value, self.layer_idx)
        positions = torch.arange(
            past_length,
            past_length + q_len,
            device=hidden_states.device,
            dtype=torch.long,
        )
        return positions.unsqueeze(0).expand(hidden_states.shape[0], -1)

    def forward(
        self,
        hidden_states: torch.Tensor,
        attention_mask: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        past_key_value: Optional[Cache] = None,
        output_attentions: bool = False,
        use_cache: bool = False,
        **kwargs,
    ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
        if "padding_mask" in kwargs:
            warnings.warn(
                "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
            )
        bsz, q_len, _ = hidden_states.size()

        # Megatron MLA applies Yarn internally from sequence length; default positions match that.
        if position_ids is None:
            position_ids = self._default_position_ids(hidden_states, past_key_value, q_len)

        if self.q_lora_rank is None:
            q = self.linear_q_proj(hidden_states)
        else:
            q = self.linear_q_up_proj(self.q_layernorm(self.linear_q_down_proj(hidden_states)))
        q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
        q_nope, q_pe = torch.split(
            q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
        )

        compressed_kv = self.linear_kv_down_proj(hidden_states)
        compressed_kv, k_pe = torch.split(
            compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
        )
        k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
        kv = (
            self.linear_kv_up_proj(self.kv_layernorm(compressed_kv))
            .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
            .transpose(1, 2)
        )

        k_nope, value_states = torch.split(
            kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
        )
        # VRS uses the current query token(s) value projection, not the full KV cache.
        vrs_value_states = value_states
        kv_seq_len = value_states.shape[-2]
        if past_key_value is not None:
            if self.layer_idx is None:
                raise ValueError(
                    f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
                    "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
                    "with a layer index."
                )
            kv_seq_len += _cache_seq_length(past_key_value, self.layer_idx)
        cos, sin = self.rotary_pos_emb(value_states, seq_len=kv_seq_len)

        q_pe, k_pe = apply_rotary_pos_emb(
            q_pe,
            k_pe,
            cos,
            sin,
            position_ids,
            rotary_interleaved=getattr(self.config, "rotary_interleaved", False),
            multi_latent_attention=True,
        )

        query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
        query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
        query_states[:, :, :, self.qk_nope_head_dim :] = q_pe

        key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
        key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
        key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
        if past_key_value is not None:
            cache_kwargs = {"sin": sin, "cos": cos}  # Specific to RoPE models
            key_states, value_states = past_key_value.update(
                key_states, value_states, self.layer_idx, cache_kwargs
            )

        attn_weights = torch.matmul(
            query_states.float(), key_states.transpose(2, 3).float()
        ) * float(self.softmax_scale)

        if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
            raise ValueError(
                f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
                f" {attn_weights.size()}"
            )
        # Megatron core attention uses causal masking when no additive mask is supplied.
        # Transformers >=5.x often leaves the prepared mask as None (SDPA/FA path), so this
        # fallback must be correct for both prefill and incremental decode, and for bsz>1.
        if attention_mask is None:
            # The q_len queries are the *last* q_len positions of the kv_seq_len keys, so the
            # diagonal must be offset by the cached prefix. With diagonal=1 a decode step
            # (q_len=1, kv_seq_len=1+past) would mask every cached key except the first.
            causal = torch.triu(
                torch.full(
                    (q_len, kv_seq_len),
                    torch.finfo(torch.float32).min,
                    device=attn_weights.device,
                    dtype=torch.float32,
                ),
                diagonal=1 + kv_seq_len - q_len,
            )
            attention_mask = causal.view(1, 1, q_len, kv_seq_len).expand(bsz, 1, q_len, kv_seq_len)
        elif attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
            if attention_mask.size() == (1, 1, q_len, kv_seq_len) and bsz > 1:
                attention_mask = attention_mask.expand(bsz, 1, q_len, kv_seq_len)
            else:
                raise ValueError(
                    f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
                )
        attn_weights = attn_weights + attention_mask.to(dtype=attn_weights.dtype)

        # upcast attention to fp32
        attn_weights = nn.functional.softmax(
            attn_weights, dim=-1, dtype=torch.float32
        ).to(query_states.dtype)
        attn_weights = nn.functional.dropout(
            attn_weights, p=self.attention_dropout, training=self.training
        )
        attn_output = torch.matmul(attn_weights, value_states)
        attn_output = _maybe_apply_vrs(
            self.config, attn_output, vrs_value_states, self.v_head_dim
        )

        if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
            raise ValueError(
                f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
                f" {attn_output.size()}"
            )

        attn_output = attn_output.transpose(1, 2).contiguous()

        attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)

        attn_output = self.linear_proj(attn_output)

        if not output_attentions:
            attn_weights = None

        return attn_output, attn_weights, past_key_value


# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->Eka-v1
class FlashAttention2(MLASelfAttention):
    """
    Eka-v1 flash attention module. Inherits MLA weights from ``MLASelfAttention``;
    only the forward path changes to call FlashAttention.
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
        # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
        # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
        self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()

    def forward(
        self,
        hidden_states: torch.Tensor,
        attention_mask: Optional[torch.LongTensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        past_key_value: Optional[Cache] = None,
        output_attentions: bool = False,
        use_cache: bool = False,
        **kwargs,
    ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
        # FlashAttention2 attention does not support output_attentions
        if "padding_mask" in kwargs:
            warnings.warn(
                "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
            )

            # overwrite attention_mask with padding_mask
            attention_mask = kwargs.pop("padding_mask")

        output_attentions = False

        bsz, q_len, _ = hidden_states.size()

        if position_ids is None:
            position_ids = self._default_position_ids(hidden_states, past_key_value, q_len)

        if self.q_lora_rank is None:
            q = self.linear_q_proj(hidden_states)
        else:
            q = self.linear_q_up_proj(self.q_layernorm(self.linear_q_down_proj(hidden_states)))
        q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
        q_nope, q_pe = torch.split(
            q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
        )

        # Flash attention requires the input to have the shape
        # batch_size x seq_length x head_dim x hidden_dim
        # therefore we just need to keep the original shape
        compressed_kv = self.linear_kv_down_proj(hidden_states)
        compressed_kv, k_pe = torch.split(
            compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
        )
        k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
        kv = (
            self.linear_kv_up_proj(self.kv_layernorm(compressed_kv))
            .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
            .transpose(1, 2)
        )

        k_nope, value_states = torch.split(
            kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
        )
        vrs_value_states = value_states
        kv_seq_len = value_states.shape[-2]
        if past_key_value is not None:
            kv_seq_len += _cache_seq_length(past_key_value, self.layer_idx)

        cos, sin = self.rotary_pos_emb(value_states, seq_len=kv_seq_len)
        q_pe, k_pe = apply_rotary_pos_emb(
            q_pe,
            k_pe,
            cos,
            sin,
            position_ids,
            rotary_interleaved=getattr(self.config, "rotary_interleaved", False),
            multi_latent_attention=True,
        )

        query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
        query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
        query_states[:, :, :, self.qk_nope_head_dim :] = q_pe

        key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
        key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
        key_states[:, :, :, self.qk_nope_head_dim :] = k_pe

        if self.q_head_dim != self.v_head_dim:
            value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])

        if past_key_value is not None:
            cache_kwargs = {"sin": sin, "cos": cos}  # Specific to RoPE models
            key_states, value_states = past_key_value.update(
                key_states, value_states, self.layer_idx, cache_kwargs
            )

        # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
        # to be able to avoid many of these transpose/reshape/view.
        query_states = query_states.transpose(1, 2)
        key_states = key_states.transpose(1, 2)
        value_states = value_states.transpose(1, 2)

        dropout_rate = self.attention_dropout if self.training else 0.0

        # In PEFT, usually we cast the layer norms in float32 for training stability reasons
        # therefore the input hidden states gets silently casted in float32. Hence, we need
        # cast them back in the correct dtype just to be sure everything works as expected.
        # This might slowdown training & inference so it is recommended to not cast the LayerNorms
        # in fp32. (RMSNorm handles it correctly)

        input_dtype = query_states.dtype
        if input_dtype == torch.float32:
            # Handle the case where the model is quantized
            if hasattr(self.config, "_pre_quantization_dtype"):
                target_dtype = self.config._pre_quantization_dtype
            elif torch.is_autocast_enabled():
                target_dtype = torch.get_autocast_gpu_dtype()
            else:
                target_dtype = (
                    self.linear_q_proj.weight.dtype
                    if self.q_lora_rank is None
                    else self.linear_q_down_proj.weight.dtype
                )

            logger.warning_once(
                f"The input hidden states seems to be silently casted in float32, this might be related to"
                f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
                f" {target_dtype}."
            )

            query_states = query_states.to(target_dtype)
            key_states = key_states.to(target_dtype)
            value_states = value_states.to(target_dtype)

        attn_output = self._flash_attention_forward(
            query_states,
            key_states,
            value_states,
            attention_mask,
            q_len,
            dropout=dropout_rate,
            softmax_scale=self.softmax_scale,
        )
        if self.q_head_dim != self.v_head_dim:
            attn_output = attn_output[:, :, :, : self.v_head_dim]

        attn_output = _maybe_apply_vrs(
            self.config,
            attn_output,
            vrs_value_states.transpose(1, 2),
            self.v_head_dim,
        )

        attn_output = attn_output.reshape(
            bsz, q_len, self.num_heads * self.v_head_dim
        ).contiguous()
        attn_output = self.linear_proj(attn_output)

        if not output_attentions:
            attn_weights = None

        return attn_output, attn_weights, past_key_value

    def _flash_attention_forward(
        self,
        query_states,
        key_states,
        value_states,
        attention_mask,
        query_length,
        dropout=0.0,
        softmax_scale=None,
    ):
        """
        Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
        first unpad the input, then computes the attention scores and pad the final attention scores.

        Args:
            query_states (`torch.Tensor`):
                Input query states to be passed to Flash Attention API
            key_states (`torch.Tensor`):
                Input key states to be passed to Flash Attention API
            value_states (`torch.Tensor`):
                Input value states to be passed to Flash Attention API
            attention_mask (`torch.Tensor`):
                The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
                position of padding tokens and 1 for the position of non-padding tokens.
            dropout (`int`, *optional*):
                Attention dropout
            softmax_scale (`float`, *optional*):
                The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
        """
        if not self._flash_attn_uses_top_left_mask:
            causal = self.is_causal
        else:
            # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in FlashAttention2 __init__.
            causal = self.is_causal and query_length != 1

        # Contains at least one padding token in the sequence
        if attention_mask is not None:
            batch_size = query_states.shape[0]
            (
                query_states,
                key_states,
                value_states,
                indices_q,
                cu_seq_lens,
                max_seq_lens,
            ) = self._upad_input(
                query_states, key_states, value_states, attention_mask, query_length
            )

            cu_seqlens_q, cu_seqlens_k = cu_seq_lens
            max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens

            attn_output_unpad = flash_attn_varlen_func(
                query_states,
                key_states,
                value_states,
                cu_seqlens_q=cu_seqlens_q,
                cu_seqlens_k=cu_seqlens_k,
                max_seqlen_q=max_seqlen_in_batch_q,
                max_seqlen_k=max_seqlen_in_batch_k,
                dropout_p=dropout,
                softmax_scale=softmax_scale,
                causal=causal,
            )

            attn_output = pad_input(
                attn_output_unpad, indices_q, batch_size, query_length
            )
        else:
            attn_output = flash_attn_func(
                query_states,
                key_states,
                value_states,
                dropout,
                softmax_scale=softmax_scale,
                causal=causal,
            )

        return attn_output

    def _upad_input(
        self, query_layer, key_layer, value_layer, attention_mask, query_length
    ):
        indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
        batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape

        key_layer = index_first_axis(
            key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
            indices_k,
        )
        value_layer = index_first_axis(
            value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
            indices_k,
        )
        if query_length == kv_seq_len:
            query_layer = index_first_axis(
                query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
                indices_k,
            )
            cu_seqlens_q = cu_seqlens_k
            max_seqlen_in_batch_q = max_seqlen_in_batch_k
            indices_q = indices_k
        elif query_length == 1:
            max_seqlen_in_batch_q = 1
            cu_seqlens_q = torch.arange(
                batch_size + 1, dtype=torch.int32, device=query_layer.device
            )  # There is a memcpy here, that is very bad.
            indices_q = cu_seqlens_q[:-1]
            query_layer = query_layer.squeeze(1)
        else:
            # The -q_len: slice assumes left padding.
            attention_mask = attention_mask[:, -query_length:]
            query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
                query_layer, attention_mask
            )

        return (
            query_layer,
            key_layer,
            value_layer,
            indices_q,
            (cu_seqlens_q, cu_seqlens_k),
            (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
        )


ATTENTION_CLASSES = {
    "eager": MLASelfAttention,
    "flash_attention_2": FlashAttention2,
}

# Deprecated alias (older export trees named the MLA module after optional VRS).
VRSMLASelfAttention = MLASelfAttention


def _resolve_hybrid_layer_kind(config: EkaV1Config, layer_idx: int) -> str:
    """Map layer index to Megatron hybrid slot.

    Nano / Eka hybrid (``get_mamba_hybrid_attention_stack_spec``):
      - ``M`` → Mamba
      - ``E`` → MoE-only
      - ``*`` → MLA attention only (MLP is ``IdentityOp`` on non-MTP trunk layers)
      - ``-`` → dense MLP-only (HF: attention path unused; rare)
    """
    pattern = getattr(config, "hybrid_override_pattern", None) or ""
    if config.enable_mamba and pattern and layer_idx < len(pattern):
        slot = pattern[layer_idx]
        if slot == "M":
            return "mamba"
        if slot == "E":
            return "moe_only"
        if slot == "*":
            # Match megatron_core: * trunk layers strip FFN (IdentityOp), MoE lives in E.
            return "attention_only"
        if slot == "-":
            return "attention"
    if _layer_uses_moe(config, layer_idx):
        return "moe"
    return "attention"


def _layer_uses_moe(config: EkaV1Config, layer_idx: int) -> bool:
    if config.n_routed_experts is None:
        return False
    if layer_idx < config.first_k_dense_replace:
        return False
    freq = config.moe_layer_freq
    if isinstance(freq, list):
        if layer_idx >= len(freq):
            return False
        return bool(freq[layer_idx])
    return layer_idx % freq == 0


class TERowParallelLinear(nn.Linear):
    """HF stand-in for Megatron ``TERowParallelLinear`` (single-GPU, TP=1)."""

    def extra_repr(self) -> str:
        return (
            f"in_features={self.in_features}, out_features={self.out_features}, "
            f"bias={self.bias is not None}, TP=1"
        )


class ColumnParallelLinear(nn.Linear):
    """HF stand-in for Megatron ``ColumnParallelLinear`` (single-GPU, TP=1)."""

    def extra_repr(self) -> str:
        return (
            f"in_features={self.in_features}, out_features={self.out_features}, "
            f"bias={self.bias is not None}, TP=1"
        )


class ExtendedRMSNorm(nn.Module):
    """Grouped RMSNorm + SiLU gate (Megatron ``ExtendedRMSNorm`` / ``RMSNormGated``).

    Prefer the mamba_ssm Triton kernel (same as Megatron) when CUDA + mamba_ssm are
    available; otherwise a fp32 PyTorch reference matching ``rms_norm_ref``.
    """

    def __init__(self, hidden_size: int, eps: float, group_size: int, norm_before_gate: bool = False):
        super().__init__()
        self.weight = nn.Parameter(torch.ones(hidden_size))
        self.eps = eps
        self.group_size = group_size
        self.norm_before_gate = norm_before_gate

    def _grouped_rms(self, x: torch.Tensor) -> torch.Tensor:
        input_dtype = x.dtype
        *lead, width = x.shape
        x_f = x.float()
        x_g = x_f.reshape(*lead, width // self.group_size, self.group_size)
        x_g = x_g * torch.rsqrt(x_g.pow(2).mean(-1, keepdim=True) + self.eps)
        x_g = x_g.reshape(*lead, width)
        return (x_g * self.weight.float()).to(input_dtype)

    def forward(self, y: torch.Tensor, z: Optional[torch.Tensor] = None) -> torch.Tensor:
        # Match Megatron ``RMSNormGated``: ``z=None`` → plain grouped RMS (mem-eff fused
        # path already applied ``silu(z)`` inside ``mamba_split_conv1d_scan_combined``).
        # Use the same Triton op Megatron subclasses (``rmsnorm_fn``) when available.
        if _mamba_rmsnorm_fn is not None and y.is_cuda:
            y_c = y.contiguous()
            z_c = z.contiguous() if z is not None else None
            w = self.weight.contiguous()
            return _mamba_rmsnorm_fn(
                y_c,
                w,
                None,
                z=z_c,
                eps=self.eps,
                group_size=self.group_size,
                norm_before_gate=self.norm_before_gate,
            )
        if z is None:
            return self._grouped_rms(y)
        gate = F.silu(z)
        if self.norm_before_gate:
            return self._grouped_rms(y) * gate
        return self._grouped_rms(y * gate)


def _eka_mamba_rms_norm(x: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor:
    """Megatron/TE fused pre-norm for Mamba in_proj: variance in fp32."""
    input_dtype = x.dtype
    x_f = x.float()
    x_f = x_f * torch.rsqrt(x_f.pow(2).mean(-1, keepdim=True) + eps)
    return (x_f * weight.float()).to(input_dtype)


def _eka_causal_conv1d(
    x: torch.Tensor,
    weight: torch.Tensor,
    bias: Optional[torch.Tensor],
    activation: str = "silu",
    left_context: Optional[torch.Tensor] = None,
) -> torch.Tensor:
    """Depthwise causal conv1d. ``x``: (B, D, L), ``weight``: (D, W).

    ``left_context`` (B, D, W-1) supplies the tokens preceding ``x`` when continuing from
    a cached conv window; without it the receptive field is zero-padded as for a fresh
    sequence.
    """
    if left_context is None and causal_conv1d_fn is not None and activation in ("silu", "swish"):
        return causal_conv1d_fn(
            x=x,
            weight=weight,
            bias=bias,
            activation=activation,
        )
    w = weight.unsqueeze(1)
    seq_len = x.shape[-1]
    if left_context is None:
        x = F.pad(x, (w.shape[-1] - 1, 0))
    else:
        x = torch.cat([left_context, x], dim=-1)
    out = F.conv1d(x, w, bias, groups=x.shape[1])
    out = out[..., -seq_len:]
    if activation in ("silu", "swish"):
        out = F.silu(out)
    return out


def _eka_selective_scan_ref(
    x: torch.Tensor,
    dt: torch.Tensor,
    A: torch.Tensor,
    B: torch.Tensor,
    C: torch.Tensor,
    D: torch.Tensor,
    dt_bias: Optional[torch.Tensor] = None,
    return_final_state: bool = False,
    initial_state: Optional[torch.Tensor] = None,
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
    """
    Reference Mamba-2 selective scan (no Triton). Shapes match ``mamba_chunk_scan_combined`` I/O.
    x: (B, L, H, P), dt: (B, L, H), A: (H,), B/C: (B, L, G, N), D: (H,)

    ``initial_state`` (B, H, P, N) continues an earlier chunk instead of starting from zero.
    """
    if dt_bias is not None:
        dt = F.softplus(dt + dt_bias)
    batch, seqlen, nheads, headdim = x.shape
    dstate = B.shape[-1]
    n_groups = B.shape[2]
    heads_per_group = nheads // n_groups
    y = torch.zeros_like(x)
    if initial_state is None:
        h = x.new_zeros(batch, nheads, headdim, dstate)
    else:
        h = initial_state.to(dtype=x.dtype).clone()
    for t in range(seqlen):
        dt_t = dt[:, t].unsqueeze(-1).unsqueeze(-1)
        B_t = B[:, t]
        C_t = C[:, t]
        x_t = x[:, t]
        for g in range(n_groups):
            hidx = slice(g * heads_per_group, (g + 1) * heads_per_group)
            # (B, N) -> (B, 1, 1, N): explicit head and head-dim axes, so this broadcasts
            # against (B, H, P, N) for any batch size rather than only for batch size 1.
            B_g = B_t[:, g].unsqueeze(1).unsqueeze(1)
            C_g = C_t[:, g].unsqueeze(1).unsqueeze(1)
            dA = torch.exp(dt_t[:, hidx] * A[hidx].view(1, -1, 1, 1))
            dB = dt_t[:, hidx] * B_g
            h[:, hidx] = dA * h[:, hidx] + dB * x_t[:, hidx].unsqueeze(-1)
            y[:, t, hidx] = (h[:, hidx] * C_g).sum(-1)
        y[:, t] = y[:, t] + x_t * D.view(1, -1, 1)
    if return_final_state:
        return y, h
    return y


def _eka_ssm_decode_ref(
    x: torch.Tensor,
    dt: torch.Tensor,
    A: torch.Tensor,
    B: torch.Tensor,
    C: torch.Tensor,
    D: torch.Tensor,
    ssm_state: torch.Tensor,
    dt_bias: torch.Tensor,
    headdim: int,
    n_groups: int,
) -> Tuple[torch.Tensor, torch.Tensor]:
    """Single-token SSM decode without Triton (matches Megatron ``_ssm_decode``)."""
    dt = F.softplus(dt + dt_bias.to(dtype=dt.dtype))
    dA = torch.exp(dt.unsqueeze(-1).unsqueeze(-1) * A.view(1, -1, 1, 1))
    x = x.view(x.shape[0], -1, headdim)
    B = B.view(x.shape[0], n_groups, -1)
    C = C.view(x.shape[0], n_groups, -1)
    heads_per_group = x.shape[1] // n_groups
    for g in range(n_groups):
        hidx = slice(g * heads_per_group, (g + 1) * heads_per_group)
        # (B, N) -> (B, 1, 1, N) so the group state broadcasts over heads and head dim
        # for any batch size (a trailing (B, 1, N) only lines up when batch size is 1).
        B_g = B[:, g].unsqueeze(1).unsqueeze(1)
        dBx = dt[:, hidx].unsqueeze(-1).unsqueeze(-1) * B_g * x[:, hidx].unsqueeze(-1)
        ssm_state[:, hidx] = ssm_state[:, hidx] * dA[:, hidx] + dBx
    y = torch.zeros(x.shape[0], x.shape[1], headdim, device=x.device, dtype=x.dtype)
    for g in range(n_groups):
        hidx = slice(g * heads_per_group, (g + 1) * heads_per_group)
        C_g = C[:, g].unsqueeze(1).unsqueeze(1)
        y[:, hidx] = (ssm_state[:, hidx] * C_g).sum(-1)
    y = y + D.view(1, -1, 1) * x
    return y.reshape(x.shape[0], -1), ssm_state


class _MambaInProjWeight(nn.Module):
    """TE-split in_proj weights (``.weight.z/x/B/C/dt``)."""

    def __init__(self, config: EkaV1Config):
        super().__init__()
        d_inner = config.mamba_num_heads * config.mamba_head_dim
        d_tot_ssm = config.mamba_state_dim * config.mamba_num_groups
        hidden = config.hidden_size
        self.z = nn.Parameter(torch.empty(d_inner, hidden))
        self.x = nn.Parameter(torch.empty(d_inner, hidden))
        self.B = nn.Parameter(torch.empty(d_tot_ssm, hidden))
        self.C = nn.Parameter(torch.empty(d_tot_ssm, hidden))
        self.dt = nn.Parameter(torch.empty(config.mamba_num_heads, hidden))


class _MambaConv1dWeight(nn.Module):
    """TE-split conv1d weight (``.weight.x/B/C``)."""

    def __init__(self, config: EkaV1Config):
        super().__init__()
        d_inner = config.mamba_num_heads * config.mamba_head_dim
        d_tot_ssm = config.mamba_state_dim * config.mamba_num_groups
        kernel = 4
        self.x = nn.Parameter(torch.empty(d_inner, 1, kernel))
        self.B = nn.Parameter(torch.empty(d_tot_ssm, 1, kernel))
        self.C = nn.Parameter(torch.empty(d_tot_ssm, 1, kernel))


class _MambaConv1dBias(nn.Module):
    """TE-split conv1d bias (``.bias.x/B/C``)."""

    def __init__(self, config: EkaV1Config):
        super().__init__()
        d_inner = config.mamba_num_heads * config.mamba_head_dim
        d_tot_ssm = config.mamba_state_dim * config.mamba_num_groups
        self.x = nn.Parameter(torch.empty(d_inner))
        self.B = nn.Parameter(torch.empty(d_tot_ssm))
        self.C = nn.Parameter(torch.empty(d_tot_ssm))


class TELayerNormColumnParallelLinear(nn.Module):
    """HF stand-in for Megatron ``TELayerNormColumnParallelLinear`` (single-GPU, TP=1)."""

    def __init__(self, config: EkaV1Config):
        super().__init__()
        self.layer_norm_weight = nn.Parameter(torch.ones(config.hidden_size))
        self.weight = _MambaInProjWeight(config)
        d_inner = config.mamba_num_heads * config.mamba_head_dim
        d_tot_ssm = config.mamba_state_dim * config.mamba_num_groups
        self._in_features = config.hidden_size
        self._out_features = d_inner * 2 + d_tot_ssm * 2 + config.mamba_num_heads

    def extra_repr(self) -> str:
        return (
            f"in_features={self._in_features}, out_features={self._out_features}, "
            f"bias=False, TP=1"
        )


class Conv1d(nn.Module):
    """HF stand-in for Megatron grouped depthwise ``Conv1d`` (single-GPU, TP=1)."""

    def __init__(self, config: EkaV1Config):
        super().__init__()
        d_inner = config.mamba_num_heads * config.mamba_head_dim
        d_tot_ssm = config.mamba_state_dim * config.mamba_num_groups
        self._channels = d_inner + 2 * d_tot_ssm
        self._kernel = getattr(config, "mamba_d_conv", 4)
        self.weight = _MambaConv1dWeight(config)
        self.bias = _MambaConv1dBias(config)

    def extra_repr(self) -> str:
        k = self._kernel
        c = self._channels
        return (
            f"{c}, {c}, kernel_size=({k},), stride=(1,), "
            f"padding=({k - 1},), groups={c}"
        )


class MambaMixer(nn.Module):
    """Megatron ``MambaMixer`` (Mamba-2 SSM block)."""

    def __init__(self, config: EkaV1Config, layer_idx: int):
        super().__init__()
        self.config = config
        self.layer_idx = layer_idx
        self.hidden_size = config.hidden_size
        self.d_inner = config.mamba_num_heads * config.mamba_head_dim
        self.d_state = config.mamba_state_dim
        self.n_groups = config.mamba_num_groups
        self.nheads = config.mamba_num_heads
        self.headdim = config.mamba_head_dim
        self.d_conv = getattr(config, "mamba_d_conv", 4)
        self.chunk_size = getattr(config, "mamba_chunk_size", 128)
        self.d_ssm = self.d_inner + 2 * self.n_groups * self.d_state

        self.in_proj = TELayerNormColumnParallelLinear(config)
        self.out_proj = TERowParallelLinear(self.d_inner, self.hidden_size, bias=False)
        self.conv1d = Conv1d(config)
        self.A_log = nn.Parameter(torch.empty(self.nheads))
        self.D = nn.Parameter(torch.ones(self.nheads))
        self.dt_bias = nn.Parameter(torch.empty(self.nheads))
        group_size = self.d_inner // self.n_groups
        # Megatron ``MambaMixer`` hardcodes ``eps=1e-5`` for ExtendedRMSNorm (not
        # ``config.layernorm_epsilon`` / HF ``rms_norm_eps``).
        self.norm = ExtendedRMSNorm(
            self.d_inner, eps=1e-5, group_size=group_size, norm_before_gate=False
        )

    def _in_proj_weight(self) -> torch.Tensor:
        """Packed ``[z; x; B; C; dt]`` weight — Megatron TE column-parallel layout."""
        w = self.in_proj.weight
        return torch.cat([w.z, w.x, w.B, w.C, w.dt], dim=0).contiguous()

    def _in_proj(self, hidden_states: torch.Tensor, layer_norm_weight: Optional[torch.Tensor] = None) -> torch.Tensor:
        # Match Megatron ``TELayerNormColumnParallelLinear``: FP32 RMS stats/scale, then
        # **one** packed GEMM (TE column-parallel ``[z;x;B;C;dt]``), not five ``F.linear``s.
        ln_weight = layer_norm_weight if layer_norm_weight is not None else self.in_proj.layer_norm_weight
        # Eka maps HF ``rms_norm_eps`` → Megatron ``layernorm_epsilon`` (both 1e-6).
        normed = _eka_mamba_rms_norm(
            hidden_states, ln_weight, self.config.rms_norm_eps
        )
        return F.linear(normed, self._in_proj_weight())

    def _conv1d_weight(self) -> torch.Tensor:
        cw = self.conv1d.weight
        return torch.cat([cw.x.squeeze(1), cw.B.squeeze(1), cw.C.squeeze(1)], dim=0).contiguous()

    def _conv1d_bias(self) -> torch.Tensor:
        cb = self.conv1d.bias
        return torch.cat([cb.x, cb.B, cb.C], dim=0).contiguous()

    def _out_proj(self, y: torch.Tensor) -> torch.Tensor:
        """TE ``TERowParallelLinear`` stand-in (TP=1, no bias)."""
        return self.out_proj(y.contiguous())

    def _ssm_training(self, zxbcdt: torch.Tensor) -> torch.Tensor:
        """Megatron ``MambaMixer._ssm_training`` without importing Megatron.

        Default (``EKA_MAMBA_FUSED_RMS=1``): fold post-RMS into
        ``mamba_split_conv1d_scan_combined`` via ``rmsnorm_weight`` / ``eps=1e-5`` /
        ``norm_before_gate=False`` — same Triton ``_layer_norm_fwd`` Megatron's
        ``ExtendedRMSNorm`` uses, composed as ``RMS(x * silu(z))``.

        ``EKA_MAMBA_FUSED_RMS=0``: literal Megatron two-step (gate in kernel, then
        ``self.norm(y)`` with z=None).
        """
        A = -torch.exp(self.A_log.float())
        zxbcdt = zxbcdt.contiguous()
        conv_w = self._conv1d_weight()
        conv_b = self._conv1d_bias()
        dt_bias = self.dt_bias.float()
        use_fused_rms = os.environ.get("EKA_MAMBA_FUSED_RMS", "1").strip().lower() not in (
            "0",
            "false",
            "no",
            "off",
        )

        common = dict(
            chunk_size=self.chunk_size,
            activation="silu",
            headdim=self.headdim,
            ngroups=self.n_groups,
            norm_before_gate=False,
        )

        if use_fused_rms:
            # Official mamba2 mem-eff + Megatron-equivalent math for
            # ``norm_before_gate=False``: Triton ``RMS(x * silu(z))`` inside the
            # kernel (same ``_layer_norm_fwd`` Megatron's ExtendedRMSNorm uses).
            # Megatron splits this as (gate-in-scan) + ``norm(y)``; folding RMS here
            # tracks that Triton op more closely in bf16 (job 315524: split+external
            # stayed at max_abs=6.375). Set ``EKA_MAMBA_FUSED_RMS=0`` for the literal
            # Megatron two-step.
            y = mamba_split_conv1d_scan_combined(
                zxbcdt,
                conv_w,
                conv_b,
                dt_bias,
                A,
                D=self.D,
                rmsnorm_weight=self.norm.weight,
                rmsnorm_eps=self.norm.eps,
                **common,
            )
            print("[eka-mamba] path=training_fused_rms", flush=True)
            return self._out_proj(y)

        # Literal Megatron ``_ssm_training``: gate in kernel, plain RMS after.
        y = mamba_split_conv1d_scan_combined(
            zxbcdt,
            conv_w,
            conv_b,
            dt_bias,
            A,
            D=self.D,
            **common,
        )
        print(
            f"[eka-mamba] path=training_split+norm rmsnorm_fn={_mamba_rmsnorm_fn is not None}",
            flush=True,
        )
        return self._out_proj(self.norm(y.contiguous()))

    def _split_zxbcdt(self, zxbcdt: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
        return torch.split(
            zxbcdt,
            [self.d_inner, self.d_ssm, self.nheads],
            dim=-1,
        )

    def _ssm_decode(
        self,
        zxbcdt: torch.Tensor,
        cache_params: Cache,
    ) -> torch.Tensor:
        zxbcdt = zxbcdt.squeeze(1)
        z, xbc, dt = self._split_zxbcdt(zxbcdt)
        conv_state = cache_params.layers[self.layer_idx].conv_states

        if causal_conv1d_update is not None:
            xbc = causal_conv1d_update(
                xbc,
                conv_state,
                self._conv1d_weight(),
                self._conv1d_bias(),
                "silu",
            )
        else:
            weight = self._conv1d_weight()  # (C, W)
            conv_state.copy_(torch.roll(conv_state, shifts=-1, dims=-1))
            conv_state[..., -1] = xbc
            xbc = (conv_state * weight.unsqueeze(0)).sum(dim=-1) + self._conv1d_bias()
            xbc = F.silu(xbc)

        x, B, C = torch.split(
            xbc,
            [self.d_inner, self.n_groups * self.d_state, self.n_groups * self.d_state],
            dim=-1,
        )
        A = -torch.exp(self.A_log.float())
        ssm_state = cache_params.layers[self.layer_idx].recurrent_states
        if ssm_state is None:
            ssm_state = x.new_zeros(x.shape[0], self.nheads, self.headdim, self.d_state)
            cache_params.update_recurrent_state(ssm_state, layer_idx=self.layer_idx)

        if selective_state_update is not None:
            A_exp = A[:, None, None].expand(-1, self.headdim, self.d_state).to(dtype=torch.float32)
            dt_h = dt[:, :, None].expand(-1, -1, self.headdim)
            dt_bias_h = self.dt_bias[:, None].expand(-1, self.headdim)
            D_h = self.D[:, None].expand(-1, self.headdim)
            B_g = B.view(x.shape[0], self.n_groups, self.d_state)
            C_g = C.view(x.shape[0], self.n_groups, self.d_state)
            x_h = x.view(x.shape[0], self.nheads, self.headdim)
            y = selective_state_update(
                ssm_state,
                x_h,
                dt_h,
                A_exp,
                B_g,
                C_g,
                D_h,
                z=None,
                dt_bias=dt_bias_h,
                dt_softplus=True,
            )
            y = y.reshape(x.shape[0], self.d_inner)
            cache_params.update_recurrent_state(ssm_state, layer_idx=self.layer_idx)
        else:
            y, ssm_state = _eka_ssm_decode_ref(
                x, dt, A, B, C, self.D, ssm_state, self.dt_bias, self.headdim, self.n_groups
            )
            cache_params.update_recurrent_state(ssm_state, layer_idx=self.layer_idx)

        y = self.norm(y, z)
        return self._out_proj(y).unsqueeze(1)

    def _ssm_prefill(
        self,
        zxbcdt: torch.Tensor,
        cache_params: Optional[Cache] = None,
    ) -> torch.Tensor:
        batch, seqlen, _ = zxbcdt.shape
        z, xbc, dt = self._split_zxbcdt(zxbcdt)
        A = -torch.exp(self.A_log.float())

        # Continuing an already-populated cache (chunked prefill, speculative verification):
        # the conv receptive field and the SSM recurrence must pick up where they left off.
        continuing = (
            cache_params is not None
            and self.layer_idx < len(cache_params.layers)
            and cache_params.has_previous_state(self.layer_idx)
        )

        xbc_t = xbc.transpose(1, 2)  # (B, C, L)
        left_context = None
        if continuing:
            cached_window = cache_params.layers[self.layer_idx].conv_states
            # Must be a copy: `update_conv_state` below rewrites `conv_states` in place.
            left_context = cached_window[..., -(self.d_conv - 1) :].to(dtype=xbc_t.dtype).clone()

        if cache_params is not None:
            if continuing:
                # Let the cache layer roll the window itself; it needs the raw new tokens.
                cache_params.update_conv_state(xbc_t, layer_idx=self.layer_idx)
            else:
                window = (
                    xbc_t[..., -self.d_conv :]
                    if seqlen >= self.d_conv
                    else F.pad(xbc_t, (self.d_conv - seqlen, 0))
                )
                cache_params.update_conv_state(window, layer_idx=self.layer_idx)

        xbc = _eka_causal_conv1d(
            xbc_t,
            self._conv1d_weight(),
            self._conv1d_bias(),
            activation="silu",
            left_context=left_context,
        ).transpose(1, 2)

        x, B, C = torch.split(
            xbc,
            [self.d_inner, self.n_groups * self.d_state, self.n_groups * self.d_state],
            dim=-1,
        )
        x = x.view(batch, seqlen, self.nheads, self.headdim)
        B = B.view(batch, seqlen, self.n_groups, self.d_state)
        C = C.view(batch, seqlen, self.n_groups, self.d_state)

        return_final_states = cache_params is not None
        initial_state = (
            cache_params.layers[self.layer_idx].recurrent_states if continuing else None
        )
        if mamba_chunk_scan_combined is not None and x.is_cuda:
            scan_out = mamba_chunk_scan_combined(
                x,
                dt,
                A,
                B,
                C,
                self.chunk_size,
                D=self.D,
                z=None,
                dt_bias=self.dt_bias.float(),
                dt_softplus=True,
                initial_states=initial_state,
                return_final_states=return_final_states,
            )
            if return_final_states:
                y, ssm_state = scan_out
                cache_params.update_recurrent_state(ssm_state, layer_idx=self.layer_idx)
            else:
                y = scan_out
        else:
            if return_final_states:
                y, ssm_state = _eka_selective_scan_ref(
                    x,
                    dt,
                    A,
                    B,
                    C,
                    self.D,
                    dt_bias=self.dt_bias,
                    return_final_state=True,
                    initial_state=initial_state,
                )
                cache_params.update_recurrent_state(ssm_state, layer_idx=self.layer_idx)
            else:
                y = _eka_selective_scan_ref(
                    x, dt, A, B, C, self.D, dt_bias=self.dt_bias, initial_state=initial_state
                )

        y = y.reshape(batch, seqlen, self.d_inner)
        y = self.norm(y, z)
        return self._out_proj(y)

    def forward(
        self,
        hidden_states: torch.Tensor,
        cache_params: Optional[Cache] = None,
        attention_mask: Optional[torch.Tensor] = None,
        layer_norm_weight: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        del attention_mask  # MambaMixer has no attention mask (unlike MLA)
        zxbcdt = self._in_proj(hidden_states, layer_norm_weight)

        if (
            cache_params is not None
            and cache_params.has_previous_state(self.layer_idx)
            and hidden_states.shape[1] == 1
        ):
            return self._ssm_decode(zxbcdt, cache_params)

        # Megatron training / parity (``inference_context is None``): mem-eff fused path.
        if (
            cache_params is None
            and hidden_states.shape[1] > 1
            and hidden_states.is_cuda
        ):
            # Lazy import — transformers remote-code load can miss mamba_ssm on first import.
            global mamba_split_conv1d_scan_combined
            if mamba_split_conv1d_scan_combined is None:
                try:
                    from mamba_ssm.ops.triton.ssd_combined import (
                        mamba_split_conv1d_scan_combined as _fn,
                    )

                    mamba_split_conv1d_scan_combined = _fn
                except ImportError:
                    pass
            if mamba_split_conv1d_scan_combined is not None:
                return self._ssm_training(zxbcdt)
            if os.environ.get("EKA_DEBUG_MAMBA", "").strip() in ("1", "true", "yes"):
                print(
                    "[eka-mamba] path=prefill_fallback "
                    "(mamba_split_conv1d_scan_combined unavailable)",
                    flush=True,
                )

        return self._ssm_prefill(zxbcdt, cache_params=cache_params)


class MambaLayer(nn.Module):
    """Megatron ``MambaLayer`` (``mixer`` + ``norm`` Identity)."""

    def __init__(self, config: EkaV1Config, layer_idx: int):
        super().__init__()
        self.layer_idx = layer_idx
        self.mixer = MambaMixer(config, layer_idx)
        self.norm = IdentityOp()

    def forward(
        self,
        hidden_states: torch.Tensor,
        attention_mask: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        past_key_value: Optional[Cache] = None,
        output_attentions: Optional[bool] = False,
        use_cache: Optional[bool] = False,
        **kwargs,
    ):
        # Megatron ``bias_dropout_add`` (eval, no bias, dropout=0):
        # cast residual to mixer dtype then residual + mixer_out.
        residual = hidden_states
        mixer_out = self.mixer(
            hidden_states,
            cache_params=past_key_value if use_cache else None,
            attention_mask=attention_mask,
        )
        if residual.dtype != mixer_out.dtype:
            residual = residual.to(dtype=mixer_out.dtype)
        hidden_states = residual + mixer_out
        outputs = (hidden_states,)
        if output_attentions:
            outputs += (None,)
        if use_cache:
            outputs += (past_key_value,)
        return outputs


class MoETransformerLayer(nn.Module):
    """Megatron ``MoETransformerLayer`` (MoE-only slot, no attention)."""

    def __init__(self, config: EkaV1Config, layer_idx: int):
        super().__init__()
        self.layer_idx = layer_idx
        self.input_layernorm = IdentityOp()
        self.self_attention = IdentityOp()
        self.pre_mlp_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        self.mlp = MoELayer(config)

    def forward(
        self,
        hidden_states: torch.Tensor,
        attention_mask: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        past_key_value: Optional[Tuple[torch.Tensor]] = None,
        output_attentions: Optional[bool] = False,
        use_cache: Optional[bool] = False,
        **kwargs,
    ):
        residual = hidden_states
        hidden_states = self.pre_mlp_layernorm(hidden_states)
        hidden_states = self.mlp(hidden_states)
        hidden_states = residual + hidden_states
        outputs = (hidden_states,)
        if output_attentions:
            outputs += (None,)
        if use_cache:
            outputs += (past_key_value,)
        return outputs


class TransformerLayer(nn.Module):
    """Megatron ``TransformerLayer`` (MLA attention ± dense/MoE MLP).

    When ``include_mlp=False`` (hybrid ``*`` trunk slots), the FFN path is omitted to
    match megatron_core ``IdentityOp`` MLP — no MoE/dense params are registered.
    """

    def __init__(
        self,
        config: EkaV1Config,
        layer_idx: int,
        force_moe: bool = False,
        include_mlp: bool = True,
    ):
        super().__init__()
        self.hidden_size = config.hidden_size
        self.layer_idx = layer_idx
        self.include_mlp = include_mlp

        self.self_attention = ATTENTION_CLASSES[config._attn_implementation](
            config=config, layer_idx=layer_idx
        )
        self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)

        if include_mlp:
            use_moe = force_moe or _layer_uses_moe(config, layer_idx)
            self.mlp = MoELayer(config) if use_moe else MLP(config)
            self.pre_mlp_layernorm = RMSNorm(
                config.hidden_size, eps=config.rms_norm_eps
            )
        else:
            # No Parameter submodules — matches ckpt (attention weights only).
            self.mlp = None
            self.pre_mlp_layernorm = None

    def forward(
        self,
        hidden_states: torch.Tensor,
        attention_mask: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        past_key_value: Optional[Tuple[torch.Tensor]] = None,
        output_attentions: Optional[bool] = False,
        use_cache: Optional[bool] = False,
        **kwargs,
    ) -> Tuple[
        torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
    ]:
        if "padding_mask" in kwargs:
            warnings.warn(
                "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
            )
        residual = hidden_states

        hidden_states = self.input_layernorm(hidden_states)

        hidden_states, self_attn_weights, present_key_value = self.self_attention(
            hidden_states=hidden_states,
            attention_mask=attention_mask,
            position_ids=position_ids,
            past_key_value=past_key_value,
            output_attentions=output_attentions,
            use_cache=use_cache,
            **kwargs,
        )
        hidden_states = residual + hidden_states

        if self.include_mlp:
            residual = hidden_states
            hidden_states = self.pre_mlp_layernorm(hidden_states)
            hidden_states = self.mlp(hidden_states)
            hidden_states = residual + hidden_states

        outputs = (hidden_states,)

        if output_attentions:
            outputs += (self_attn_weights,)

        if use_cache:
            outputs += (present_key_value,)

        return outputs


def _build_decoder_layer(config: EkaV1Config, layer_idx: int) -> nn.Module:
    kind = _resolve_hybrid_layer_kind(config, layer_idx)
    if kind == "mamba":
        return MambaLayer(config, layer_idx)
    if kind == "moe_only":
        return MoETransformerLayer(config, layer_idx)
    if kind == "attention_only":
        return TransformerLayer(config, layer_idx, include_mlp=False)
    if kind == "attention_moe":
        return TransformerLayer(config, layer_idx, force_moe=True)
    return TransformerLayer(config, layer_idx, force_moe=(kind == "moe"))

class MambaStack(nn.Module):
    """Megatron ``MambaStack`` (decoder layer stack + ``final_norm``)."""

    def __init__(self, config: EkaV1Config):
        super().__init__()
        self.layers = nn.ModuleList(
            [_build_decoder_layer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
        )
        self.final_norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)


EkaV1_START_DOCSTRING = r"""
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`EkaV1Config`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""


@add_start_docstrings(
    "The bare EkaV1 Model outputting raw hidden-states without any specific head on top.",
    EkaV1_START_DOCSTRING,
)
class EkaV1PreTrainedModel(PreTrainedModel):
    config_class = EkaV1Config
    base_model_prefix = "model"
    supports_gradient_checkpointing = True
    _no_split_modules = ["TransformerLayer"]
    _skip_keys_device_placement = "past_key_values"
    _supports_flash_attn_2 = True
    _supports_cache_class = True

    @classmethod
    def _supports_default_dynamic_cache(cls) -> bool:
        """Prevent transformers generate() from pre-creating a plain DynamicCache.

        Eka-V1 is a Mamba+MLA hybrid: the cache needs DynamicLayer slots for
        attention layers and LinearAttentionLayer slots for Mamba layers.  A bare
        DynamicCache() built by ``_prepare_cache_for_generation`` has the wrong
        layout and is rejected by ``EkaV1Model._prepare_cache``.  Returning False
        here makes generate() skip its default cache init, so the model's own
        ``_prepare_cache`` in forward() builds the correct hybrid cache via
        ``build_eka_cache(config)``.
        """
        return False
    # Do not set `_keep_in_fp32_modules[_strict]` to buffer names: this transformers
    # build requires those entries to be real submodule names and raises in post_init.
    # Router bias stays float32 via register_buffer(dtype=fp32) + _reload_router_expert_bias_fp32.

    def _init_weights(self, module):
        std = self.config.initializer_range
        if isinstance(module, nn.Linear):
            module.weight.data.normal_(mean=0.0, std=std)
            if module.bias is not None:
                module.bias.data.zero_()
        elif isinstance(module, nn.Embedding):
            module.weight.data.normal_(mean=0.0, std=std)
            if module.padding_idx is not None:
                module.weight.data[module.padding_idx].zero_()
        elif isinstance(module, TopKRouter):
            if hasattr(module, "e_score_correction_bias"):
                module.e_score_correction_bias.data.zero_()
                module._maintain_float32_expert_bias()

    @classmethod
    def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
        model = super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
        model._reload_router_expert_bias_fp32(pretrained_model_name_or_path)
        return model

    def to(self, *args, **kwargs):
        result = super().to(*args, **kwargs)
        for module in result.modules():
            if isinstance(module, TopKRouter):
                module._maintain_float32_expert_bias()
        return result

    def _reload_router_expert_bias_fp32(self, model_path) -> None:
        """Re-load router biases as float32 from disk after bf16 ``from_pretrained`` casts.

        Megatron ``expert_bias`` is float32 (~38.02 with small per-expert deltas). Casting
        to bf16 rounds them all to 38.0 and destroys top-k routing. Prefer values from
        safetensors / bin (exported as float32) over the already-rounded in-memory copy.
        """
        from pathlib import Path

        path = Path(model_path) if model_path is not None else None
        if path is None or not path.exists():
            for module in self.modules():
                if isinstance(module, TopKRouter):
                    module._maintain_float32_expert_bias()
            return

        bias_tensors: dict = {}
        st_files = sorted(path.glob("*.safetensors"))
        if st_files:
            from safetensors import safe_open

            for st_path in st_files:
                with safe_open(st_path, framework="pt", device="cpu") as f:
                    for key in f.keys():
                        if key.endswith("e_score_correction_bias"):
                            bias_tensors[key] = f.get_tensor(key).to(torch.float32)
        else:
            bin_path = path / "pytorch_model.bin"
            if bin_path.exists():
                raw = torch.load(bin_path, map_location="cpu")
                for key, tensor in raw.items():
                    if key.endswith("e_score_correction_bias"):
                        bias_tensors[key] = tensor.to(torch.float32)

        if not bias_tensors:
            for module in self.modules():
                if isinstance(module, TopKRouter):
                    module._maintain_float32_expert_bias()
            return

        name_to_module = dict(self.named_modules())
        for key, tensor in bias_tensors.items():
            # key: model.decoder.layers.N.mlp.router.e_score_correction_bias
            module_name, _, attr = key.rpartition(".")
            module = name_to_module.get(module_name)
            if module is None or not hasattr(module, attr):
                continue
            buf = getattr(module, attr)
            device = buf.device if isinstance(buf, torch.Tensor) else tensor.device
            with torch.no_grad():
                if attr in getattr(module, "_parameters", {}):
                    del module._parameters[attr]
                module.register_buffer(
                    attr, tensor.to(device=device, dtype=torch.float32)
                )
            if isinstance(module, TopKRouter):
                module._maintain_float32_expert_bias()


EkaV1_INPUTS_DOCSTRING = r"""
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
            `past_key_values`).

            If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
            and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
            information on the default strategy.

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.n_positions - 1]`.

            [What are position IDs?](../glossary#position-ids)
        past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
            Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
            blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
            returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

            Two formats are allowed:
            - a [`~cache_utils.Cache`] instance;
            - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
            shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
            cache format.

            The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
            legacy cache format will be returned.

            If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
            have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
            of shape `(batch_size, sequence_length)`.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""


@add_start_docstrings(
    "The bare Eka-v1 Model outputting raw hidden-states without any specific head on top.",
    EkaV1_START_DOCSTRING,
)
class EkaV1Model(EkaV1PreTrainedModel):
    """
    Megatron-style backbone: ``embedding`` + ``decoder`` (``MambaStack``).

    Args:
        config: EkaV1Config
    """

    def __init__(self, config: EkaV1Config):
        super().__init__(config)
        self.padding_idx = config.pad_token_id
        self.vocab_size = config.vocab_size

        self.embedding = LanguageModelEmbedding(config)
        self.decoder = MambaStack(config)
        self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"

        self.gradient_checkpointing = False
        self.post_init()

    @property
    def embed_tokens(self) -> nn.Embedding:
        """HF API alias for ``embedding.word_embeddings``."""
        return self.embedding.word_embeddings

    @embed_tokens.setter
    def embed_tokens(self, value: nn.Embedding) -> None:
        self.embedding.word_embeddings = value

    def get_input_embeddings(self):
        return self.embedding.word_embeddings

    def set_input_embeddings(self, value):
        self.embedding.word_embeddings = value

    def _prepare_cache(self, past_key_values: Optional[Cache]) -> Cache:
        """Return a cache whose per-layer slots match this model's hybrid stack.

        A generic ``DynamicCache()`` has no layers until its first ``update``, and grows
        KV-only slots; the Mamba layers here need ``LinearAttentionLayer`` slots at their
        own indices. An empty cache is therefore replaced, and a populated but
        incompatible one is rejected rather than silently dropping the SSM state.
        """
        if past_key_values is None or len(getattr(past_key_values, "layers", [])) == 0:
            return build_eka_cache(self.config)

        expected_attention = {
            idx
            for idx in range(self.config.num_hidden_layers)
            if _eka_cache_slot_is_stateful_attention(self.config, idx)
        }
        if set(_attention_layer_indices(past_key_values)) != expected_attention:
            raise ValueError(
                f"{type(past_key_values).__name__} does not match the Eka-V1 hybrid layout: "
                "Mamba layers need linear-attention slots and MLA layers need key/value slots. "
                "Pass `past_key_values=None` to let the model build one, or build it explicitly "
                "with `modeling_eka.build_eka_cache(model.config)`."
            )
        return past_key_values

    @add_start_docstrings_to_model_forward(EkaV1_INPUTS_DOCSTRING)
    def forward(
        self,
        input_ids: torch.LongTensor = None,
        attention_mask: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        past_key_values: Optional[List[torch.FloatTensor]] = None,
        inputs_embeds: Optional[torch.FloatTensor] = None,
        use_cache: Optional[bool] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
        cache_position: Optional[torch.LongTensor] = None,
        **kwargs,
    ) -> Union[Tuple, BaseModelOutputWithPast]:
        output_attentions = (
            output_attentions
            if output_attentions is not None
            else self.config.output_attentions
        )
        output_hidden_states = (
            output_hidden_states
            if output_hidden_states is not None
            else self.config.output_hidden_states
        )
        use_cache = use_cache if use_cache is not None else self.config.use_cache

        return_dict = (
            return_dict if return_dict is not None else self.config.use_return_dict
        )

        # retrieve input_ids and inputs_embeds
        if input_ids is not None and inputs_embeds is not None:
            raise ValueError(
                "You cannot specify both input_ids and inputs_embeds at the same time"
            )
        elif input_ids is not None:
            batch_size, seq_length = input_ids.shape[:2]
        elif inputs_embeds is not None:
            batch_size, seq_length = inputs_embeds.shape[:2]
        else:
            raise ValueError("You have to specify either input_ids or inputs_embeds")

        past_key_values_length = 0
        if use_cache:
            past_key_values = self._prepare_cache(past_key_values)
            past_key_values_length = _cache_seq_length(past_key_values)

        if position_ids is None:
            device = input_ids.device if input_ids is not None else inputs_embeds.device
            position_ids = torch.arange(
                past_key_values_length,
                seq_length + past_key_values_length,
                dtype=torch.long,
                device=device,
            )
            position_ids = position_ids.unsqueeze(0)

        if inputs_embeds is None:
            inputs_embeds = self.embedding(input_ids)

        attention_mask = _eka_prepare_attention_mask(
            self.config,
            attention_mask,
            batch_size,
            seq_length,
            inputs_embeds,
            past_key_values_length,
        )

        # embed positions
        hidden_states = inputs_embeds

        # decoder layers
        all_hidden_states = () if output_hidden_states else None
        all_self_attns = () if output_attentions else None
        next_decoder_cache = None

        for decoder_layer in self.decoder.layers:
            if output_hidden_states:
                all_hidden_states += (hidden_states,)

            layer_outputs = decoder_layer(
                hidden_states,
                attention_mask=attention_mask,
                position_ids=position_ids,
                past_key_value=past_key_values,
                output_attentions=output_attentions,
                use_cache=use_cache,
            )

            hidden_states = layer_outputs[0]

            if use_cache:
                next_decoder_cache = layer_outputs[2 if output_attentions else 1]

            if output_attentions:
                all_self_attns += (layer_outputs[1],)

        hidden_states = self.decoder.final_norm(hidden_states)

        # add hidden states from the last decoder layer
        if output_hidden_states:
            all_hidden_states += (hidden_states,)

        next_cache = next_decoder_cache if use_cache else None
        if not return_dict:
            return tuple(
                v
                for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
                if v is not None
            )
        return BaseModelOutputWithPast(
            last_hidden_state=hidden_states,
            past_key_values=next_cache,
            hidden_states=all_hidden_states,
            attentions=all_self_attns,
        )


def _roll_mtp_tensor(tensor: torch.Tensor, shifts: int = -1, pad_value: int = 0) -> torch.Tensor:
    """Roll along the sequence dimension and zero/pad the exposed tail (Megatron ``roll_tensor``)."""
    rolled = torch.roll(tensor, shifts=shifts, dims=-1)
    if shifts < 0:
        rolled[..., shifts:] = pad_value
    return rolled


class MultiTokenPredictionLayer(nn.Module):
    """One Megatron ``mtp.layers.*`` block (DeepSeek-V3 style MTP depth).

    Training uses the full-sequence ``forward`` (roll + causal self-attention, no cache).
    Speculative decoding uses ``draft_step`` with a dedicated MTP KV cache so each depth
    can attend to previously accepted draft positions (MTP Vanilla / Eagle decode form).
    """

    def __init__(self, config: EkaV1Config, layer_idx: int = 0):
        super().__init__()
        self.config = config
        self.mtp_layer_idx = layer_idx
        self.eh_proj = nn.Linear(config.hidden_size * 2, config.hidden_size, bias=False)
        self.enorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        self.hnorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        self.final_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        # Index into the *MTP* cache (``build_mtp_cache``), not the hybrid trunk cache.
        self.transformer_layer = TransformerLayer(
            config,
            layer_idx=layer_idx,
            force_moe=True,
        )

    def _combine_and_transform(
        self,
        hidden_states: torch.Tensor,
        token_embeds: torch.Tensor,
        attention_mask: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        past_key_value: Optional[Cache] = None,
        use_cache: bool = False,
        **kwargs,
    ) -> torch.Tensor:
        """Shared core: norm → concat → project → transformer → final RMSNorm."""
        decoder_input = self.enorm(token_embeds)
        hidden_states = self.hnorm(hidden_states)
        hidden_states = self.eh_proj(torch.cat([decoder_input, hidden_states], dim=-1))

        bsz, seq_len = hidden_states.shape[:2]
        past_len = 0
        cache_for_attn = past_key_value if use_cache else None
        if cache_for_attn is not None:
            past_len = _cache_seq_length(cache_for_attn, self.transformer_layer.layer_idx)

        if position_ids is None and past_len > 0:
            position_ids = (
                torch.arange(
                    past_len,
                    past_len + seq_len,
                    device=hidden_states.device,
                    dtype=torch.long,
                )
                .unsqueeze(0)
                .expand(bsz, -1)
            )

        layer_attention_mask = _eka_prepare_attention_mask(
            self.config,
            attention_mask,
            bsz,
            seq_len,
            hidden_states,
            past_key_values_length=past_len,
        )
        hidden_states = self.transformer_layer(
            hidden_states,
            attention_mask=layer_attention_mask,
            position_ids=position_ids,
            past_key_value=cache_for_attn,
            use_cache=use_cache,
            **kwargs,
        )[0]
        return self.final_layernorm(hidden_states)

    def forward(
        self,
        hidden_states: torch.Tensor,
        input_ids: torch.LongTensor,
        embed_tokens: nn.Embedding,
        position_ids: Optional[torch.LongTensor] = None,
        attention_mask: Optional[torch.Tensor] = None,
        **kwargs,
    ) -> Tuple[torch.Tensor, torch.LongTensor, Optional[torch.LongTensor]]:
        # Megatron ``roll_tensor`` always zero-fills the exposed tail (not pad_token_id).
        rolled_ids = _roll_mtp_tensor(input_ids, pad_value=0)
        rolled_position_ids = (
            _roll_mtp_tensor(position_ids, pad_value=0) if position_ids is not None else None
        )

        # Training / parity path: full sequence, no MTP cache.
        # Megatron MLA Yarn is applied from sequence length (positions 0..S-1), not from
        # the rolled position_ids used only for the shared embedding path.
        kwargs.pop("past_key_value", None)
        kwargs.pop("use_cache", None)
        hidden_states = self._combine_and_transform(
            hidden_states,
            embed_tokens(rolled_ids),
            attention_mask=attention_mask,
            position_ids=None,
            past_key_value=None,
            use_cache=False,
            **kwargs,
        )
        return hidden_states, rolled_ids, rolled_position_ids

    def draft_step(
        self,
        hidden_states: torch.Tensor,
        next_token_ids: torch.LongTensor,
        embed_tokens: nn.Embedding,
        past_key_value: Optional[Cache] = None,
        use_cache: bool = True,
        **kwargs,
    ) -> torch.Tensor:
        """Single-position speculative draft step with optional MTP KV cache.

        ``hidden_states`` is ``(batch, 1, hidden)`` from the previous depth (trunk at depth 0).
        ``next_token_ids`` is ``(batch,)`` or ``(batch, 1)`` — the already-predicted token whose
        embedding plays the role of the training-time rolled input at this position.
        """
        if next_token_ids.dim() == 1:
            next_token_ids = next_token_ids.unsqueeze(-1)
        elif next_token_ids.dim() != 2:
            raise ValueError(
                f"next_token_ids must be (batch,) or (batch, 1), got {tuple(next_token_ids.shape)}"
            )
        if hidden_states.shape[1] != 1:
            raise ValueError(
                f"draft_step expects a single position, got seq_len={hidden_states.shape[1]}"
            )
        return self._combine_and_transform(
            hidden_states,
            embed_tokens(next_token_ids),
            attention_mask=None,
            position_ids=None,
            past_key_value=past_key_value,
            use_cache=use_cache,
            **kwargs,
        )


class MultiTokenPredictionBlock(nn.Module):
    """Megatron ``MultiTokenPredictionBlock`` (batch-first: concat on ``seq`` dim)."""

    def __init__(self, config: EkaV1Config):
        super().__init__()
        num_layers = _mtp_num_layers_from_config(config)
        self.layers = nn.ModuleList(
            [MultiTokenPredictionLayer(config, layer_idx=i) for i in range(num_layers)]
        )

    def forward(
        self,
        hidden_states: torch.Tensor,
        input_ids: torch.LongTensor,
        embed_tokens: nn.Embedding,
        position_ids: Optional[torch.LongTensor] = None,
        attention_mask: Optional[torch.Tensor] = None,
        **kwargs,
    ) -> torch.Tensor:
        hidden_states_list = [hidden_states]
        cur_hidden = hidden_states
        cur_ids = input_ids
        cur_pos = position_ids
        for layer in self.layers:
            cur_hidden, cur_ids, cur_pos = layer(
                cur_hidden,
                cur_ids,
                embed_tokens,
                position_ids=cur_pos,
                attention_mask=attention_mask,
                **kwargs,
            )
            hidden_states_list.append(cur_hidden)
        return torch.cat(hidden_states_list, dim=1)

    def draft_tokens(
        self,
        last_hidden: torch.Tensor,
        first_next_token: torch.LongTensor,
        embed_tokens: nn.Embedding,
        output_layer: nn.Module,
        mtp_cache: Optional[Cache] = None,
        use_cache: bool = True,
    ) -> List[int]:
        """Greedy draft chain from MTP depths (batch size 1), updating ``mtp_cache``.

        Depth 0 combines ``last_hidden`` with ``Emb(first_next_token)`` and predicts the
        first draft; each subsequent depth feeds the previous draft's embedding. Each depth
        writes one new KV entry into its MTP cache slot when ``use_cache`` is set.
        """
        if last_hidden.shape[0] != 1:
            raise ValueError("MTP draft_tokens currently supports batch_size=1 only")
        if last_hidden.dim() == 2:
            last_hidden = last_hidden.unsqueeze(1)
        elif last_hidden.shape[1] != 1:
            last_hidden = last_hidden[:, -1:, :]

        if isinstance(first_next_token, int):
            next_ids = torch.tensor([first_next_token], device=last_hidden.device, dtype=torch.long)
        else:
            next_ids = first_next_token.view(-1).to(device=last_hidden.device, dtype=torch.long)

        drafts: List[int] = []
        cur_hidden = last_hidden
        for layer in self.layers:
            cur_hidden = layer.draft_step(
                cur_hidden,
                next_ids,
                embed_tokens,
                past_key_value=mtp_cache,
                use_cache=use_cache and mtp_cache is not None,
            )
            draft_id = int(output_layer(cur_hidden[:, -1, :]).float().argmax(dim=-1).item())
            drafts.append(draft_id)
            next_ids = torch.tensor([draft_id], device=last_hidden.device, dtype=torch.long)
        return drafts


class EkaV1ForCausalLM(EkaV1PreTrainedModel, GenerationMixin):
    """Causal LM with root-level ``mtp`` / ``output_layer`` (Megatron + bridge key layout).

    Bridge weight keys are ``mtp.layers.*`` / ``output_layer.*``, not ``model.mtp.*``.
    Keep MTP beside ``self.model`` so export/parity match Megatron without remapping.
    """

    _tied_weights_keys = {}  # transformers>=5 expects a mapping; embeddings are untied

    @classmethod
    def _supports_default_dynamic_cache(cls):
        # EKA builds its own hybrid cache (build_eka_cache); a stock DynamicCache
        # lacks has_previous_state and the Mamba conv/ssm state buffers.
        return False

    def __init__(self, config, **kwargs):
        super().__init__(config, **kwargs)
        self.model = EkaV1Model(config)
        self.vocab_size = config.vocab_size
        self.output_layer = ColumnParallelLinear(config.hidden_size, config.vocab_size, bias=False)
        mtp_layers = getattr(config, "mtp_num_layers", None) or getattr(
            config, "num_nextn_predict_layers", 0
        )
        if mtp_layers:
            self.mtp = MultiTokenPredictionBlock(config)

        qcfg = getattr(config, "eka_quantization", None)
        if isinstance(qcfg, dict):
            replace_linear_with_quant(self, int(qcfg["bits"]), int(qcfg.get("group_size", 64)))

        # Initialize weights and apply final processing
        self.post_init()

    def get_input_embeddings(self):
        return self.model.embedding.word_embeddings

    def set_input_embeddings(self, value):
        self.model.embedding.word_embeddings = value

    def get_output_embeddings(self):
        return self.output_layer

    def set_output_embeddings(self, new_embeddings):
        self.output_layer = new_embeddings

    @property
    def lm_head(self) -> nn.Linear:
        """HF API alias for ``output_layer``."""
        return self.output_layer

    @lm_head.setter
    def lm_head(self, value: nn.Linear) -> None:
        self.output_layer = value

    def set_decoder(self, decoder):
        self.model = decoder

    def get_decoder(self):
        return self.model

    @add_start_docstrings_to_model_forward(EkaV1_INPUTS_DOCSTRING)
    @replace_return_docstrings(
        output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
    )
    def forward(
        self,
        input_ids: torch.LongTensor = None,
        attention_mask: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        past_key_values: Optional[List[torch.FloatTensor]] = None,
        inputs_embeds: Optional[torch.FloatTensor] = None,
        labels: Optional[torch.LongTensor] = None,
        use_cache: Optional[bool] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
        cache_position: Optional[torch.LongTensor] = None,
        **kwargs,
    ) -> Union[Tuple, CausalLMOutputWithPast]:
        r"""
        Args:
            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
                (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.

        Returns:

        Example:

        ```python
        >>> from transformers import AutoTokenizer, EkaV1ForCausalLM

        >>> model = EkaV1ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
        >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)

        >>> prompt = "Hey, are you conscious? Can you talk to me?"
        >>> inputs = tokenizer(prompt, return_tensors="pt")

        >>> # Generate
        >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
        >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
        ```"""
        output_attentions = (
            output_attentions
            if output_attentions is not None
            else self.config.output_attentions
        )
        output_hidden_states = (
            output_hidden_states
            if output_hidden_states is not None
            else self.config.output_hidden_states
        )
        return_dict = (
            return_dict if return_dict is not None else self.config.use_return_dict
        )

        # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
        outputs = self.model(
            input_ids=input_ids,
            attention_mask=attention_mask,
            position_ids=position_ids,
            past_key_values=past_key_values,
            inputs_embeds=inputs_embeds,
            use_cache=use_cache,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        hidden_states = outputs[0]

        run_mtp = (
            labels is not None
            and input_ids is not None
            and hasattr(self, "mtp")
            and self.mtp is not None
            and len(self.mtp.layers) > 0
        )
        if run_mtp:
            mtp_hidden = self.mtp(
                hidden_states,
                input_ids=input_ids,
                embed_tokens=self.model.embed_tokens,
                position_ids=position_ids,
                attention_mask=attention_mask,
            )
            num_mtp = len(self.mtp.layers)
            hidden_states_list = torch.chunk(mtp_hidden, 1 + num_mtp, dim=1)
            hidden_states = hidden_states_list[0]

        logits = self.output_layer(hidden_states)
        logits = logits.float()

        loss = None
        if labels is not None:
            shift_logits = logits[..., :-1, :].contiguous()
            shift_labels = labels[..., 1:].contiguous()
            loss_fct = CrossEntropyLoss()
            shift_logits = shift_logits.view(-1, self.config.vocab_size)
            shift_labels = shift_labels.view(-1)
            shift_labels = shift_labels.to(shift_logits.device)
            loss = loss_fct(shift_logits, shift_labels)

            if run_mtp:
                mtp_scale = getattr(self.config, "mtp_loss_scaling_factor", 0.1) / num_mtp
                mtp_labels = labels.clone()
                for mtp_idx in range(num_mtp):
                    mtp_logits = self.output_layer(hidden_states_list[mtp_idx + 1]).float()
                    mtp_shift_logits = mtp_logits[..., :-1, :].contiguous()
                    mtp_shift_labels = mtp_labels[..., 1:].contiguous()
                    mtp_shift_logits = mtp_shift_logits.view(-1, self.config.vocab_size)
                    mtp_shift_labels = mtp_shift_labels.view(-1).to(mtp_shift_logits.device)
                    loss = loss + mtp_scale * loss_fct(mtp_shift_logits, mtp_shift_labels)
                    mtp_labels = _roll_mtp_tensor(mtp_labels, pad_value=-100)

        if not return_dict:
            output = (logits,) + outputs[1:]
            return (loss,) + output if loss is not None else output

        return CausalLMOutputWithPast(
            loss=loss,
            logits=logits,
            past_key_values=outputs.past_key_values,
            hidden_states=outputs.hidden_states,
            attentions=outputs.attentions,
        )

    def _mtp_num_layers(self) -> int:
        if not hasattr(self, "mtp") or self.mtp is None:
            return 0
        return len(self.mtp.layers)

    def _greedy_argmax_last(self, hidden_states: torch.Tensor) -> int:
        return int(self.output_layer(hidden_states[:, -1, :]).float().argmax(dim=-1).item())

    def _mtp_forward_cached(
        self,
        past_key_values: Optional[Cache],
        attention_mask: Optional[torch.Tensor],
        new_token_ids: List[int],
        device: torch.device,
    ) -> Tuple[Cache, torch.Tensor, Optional[torch.Tensor]]:
        """Extend the trunk KV/SSM cache with ``new_token_ids``; return cache + last hidden."""
        if not new_token_ids:
            raise ValueError("new_token_ids must be non-empty")
        input_ids = torch.tensor([new_token_ids], dtype=torch.long, device=device)
        if past_key_values is None:
            step_attention_mask = torch.ones_like(input_ids)
        else:
            past_len = _cache_seq_length(past_key_values)
            step_attention_mask = torch.ones(
                (1, past_len + input_ids.shape[1]),
                dtype=torch.long,
                device=device,
            )
        outputs = self.model(
            input_ids=input_ids,
            attention_mask=step_attention_mask,
            past_key_values=past_key_values,
            use_cache=True,
            return_dict=True,
        )
        # ``step_attention_mask`` already spans the full cached prefix + new tokens.
        return outputs.past_key_values, outputs.last_hidden_state, step_attention_mask

    def _mtp_draft_ids(
        self,
        last_hidden: torch.Tensor,
        main_next: int,
        mtp_cache: Optional[Cache] = None,
    ) -> List[int]:
        """Run the MTP tower once to draft ``mtp_num_layers`` tokens after ``main_next``."""
        return self.mtp.draft_tokens(
            last_hidden[:, -1:, :],
            first_next_token=main_next,
            embed_tokens=self.model.embed_tokens,
            output_layer=self.output_layer,
            mtp_cache=mtp_cache,
            use_cache=mtp_cache is not None,
        )

    @torch.inference_mode()
    def mtp_speculative_generate(
        self,
        input_ids: torch.LongTensor,
        max_new_tokens: int = 128,
        do_sample: bool = False,
        eos_token_id: Optional[int] = None,
        pad_token_id: Optional[int] = None,
        **kwargs,
    ) -> torch.LongTensor:
        """Greedy generation with DeepSeek MTP draft-and-verify + MTP KV cache.

        Algorithm (batch size 1, greedy only):
          1. Prefill the prompt into the hybrid **trunk** cache.
          2. Sample the next token from the trunk (always accepted).
          3. Draft up to ``mtp_num_layers`` further tokens via MTP ``draft_step``, writing
             each depth into a dedicated **MTP KV cache** (separate from the trunk).
          4. Verify drafts against the trunk one token at a time. On mismatch, accept the
             trunk's bonus token and **rewind** the MTP cache to drop rejected draft KVs.

        Because every emitted token is trunk-verified, the output matches plain greedy
        decoding; MTP cache only improves draft quality / cost across steps.
        """
        if do_sample:
            raise ValueError(
                "mtp_speculative_generate only supports greedy decoding (do_sample=False)."
            )
        if input_ids.shape[0] != 1:
            raise ValueError(
                "mtp_speculative_generate currently supports batch_size=1 only; "
                "use generate() for batched decoding."
            )

        num_mtp = self._mtp_num_layers()
        if num_mtp == 0:
            return self.generate(
                input_ids=input_ids,
                max_new_tokens=max_new_tokens,
                do_sample=False,
                eos_token_id=eos_token_id,
                pad_token_id=pad_token_id,
                **kwargs,
            )

        device = input_ids.device
        tokens = input_ids[0].tolist()
        generated = 0
        mtp_cache = build_mtp_cache(self.config)

        past_key_values, last_hidden, attention_mask = self._mtp_forward_cached(
            None,
            None,
            tokens,
            device,
        )

        while generated < max_new_tokens:
            main_next = self._greedy_argmax_last(last_hidden)
            # Snapshot MTP lengths before speculative writes so we can rewind rejects.
            mtp_lens_before = _mtp_cache_lengths(mtp_cache)
            draft_ids = self._mtp_draft_ids(last_hidden, main_next, mtp_cache=mtp_cache)
            candidates = [main_next] + draft_ids

            # How many MTP draft tokens (not counting main_next) were accepted this round.
            accepted_drafts = 0

            for i, cand in enumerate(candidates):
                if generated >= max_new_tokens:
                    break

                if i > 0:
                    verify_next = self._greedy_argmax_last(last_hidden)
                    if verify_next != cand:
                        # Bonus token from the verifier; stop this draft round.
                        past_key_values, last_hidden, attention_mask = self._mtp_forward_cached(
                            past_key_values,
                            attention_mask,
                            [verify_next],
                            device,
                        )
                        tokens.append(verify_next)
                        generated += 1
                        if eos_token_id is not None and verify_next == eos_token_id:
                            return torch.tensor([tokens], dtype=torch.long, device=device)
                        break

                    accepted_drafts += 1

                past_key_values, last_hidden, attention_mask = self._mtp_forward_cached(
                    past_key_values,
                    attention_mask,
                    [cand],
                    device,
                )
                tokens.append(cand)
                generated += 1
                if eos_token_id is not None and cand == eos_token_id:
                    return torch.tensor([tokens], dtype=torch.long, device=device)

            # Keep MTP KV only for accepted draft depths; drop the rejected suffix.
            # Depth i wrote one entry during drafting; retain the first ``accepted_drafts``.
            target_lens = [
                mtp_lens_before[depth] + (1 if depth < accepted_drafts else 0)
                for depth in range(num_mtp)
            ]
            _rewind_mtp_cache(mtp_cache, target_lens)

        return torch.tensor([tokens], dtype=torch.long, device=device)

    def prepare_inputs_for_generation(
        self,
        input_ids,
        past_key_values=None,
        attention_mask=None,
        inputs_embeds=None,
        **kwargs,
    ):
        # Transformers 5.x generate() passes full-length position_ids in model_kwargs and
        # relies on the base implementation to slice them to next_sequence_length.
        return super().prepare_inputs_for_generation(
            input_ids,
            past_key_values=past_key_values,
            attention_mask=attention_mask,
            inputs_embeds=inputs_embeds,
            **kwargs,
        )

    @staticmethod
    def _reorder_cache(past_key_values, beam_idx):
        # Beam search must reorder the Mamba conv/SSM state as well as the MLA key/values;
        # `Cache.reorder_cache` dispatches to the right routine per slot. Iterating the
        # cache as legacy `(key, value)` tuples would drop the SSM state entirely.
        past_key_values.reorder_cache(beam_idx)
        return past_key_values


@add_start_docstrings(
    """
    The Eka-v1 Model transformer with a sequence classification head on top (linear layer).

    [`EkaV1ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
    (e.g. GPT-2) do.

    Since it does classification on the last token, it requires to know the position of the last token. If a
    `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
    no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
    padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
    each row of the batch).
    """,
    EkaV1_START_DOCSTRING,
)
class EkaV1ForSequenceClassification(EkaV1PreTrainedModel):
    def __init__(self, config):
        super().__init__(config)
        self.num_labels = config.num_labels
        self.model = EkaV1Model(config)
        self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)

        # Initialize weights and apply final processing
        self.post_init()

    def get_input_embeddings(self):
        return self.model.embed_tokens

    def set_input_embeddings(self, value):
        self.model.embed_tokens = value

    @add_start_docstrings_to_model_forward(EkaV1_INPUTS_DOCSTRING)
    def forward(
        self,
        input_ids: torch.LongTensor = None,
        attention_mask: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        past_key_values: Optional[List[torch.FloatTensor]] = None,
        inputs_embeds: Optional[torch.FloatTensor] = None,
        labels: Optional[torch.LongTensor] = None,
        use_cache: Optional[bool] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
        r"""
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        """
        return_dict = (
            return_dict if return_dict is not None else self.config.use_return_dict
        )

        transformer_outputs = self.model(
            input_ids,
            attention_mask=attention_mask,
            position_ids=position_ids,
            past_key_values=past_key_values,
            inputs_embeds=inputs_embeds,
            use_cache=use_cache,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )
        hidden_states = transformer_outputs[0]
        logits = self.score(hidden_states)

        if input_ids is not None:
            batch_size = input_ids.shape[0]
        else:
            batch_size = inputs_embeds.shape[0]

        if self.config.pad_token_id is None and batch_size != 1:
            raise ValueError(
                "Cannot handle batch sizes > 1 if no padding token is defined."
            )
        if self.config.pad_token_id is None:
            sequence_lengths = -1
        else:
            if input_ids is not None:
                sequence_lengths = (
                    torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
                ).to(logits.device)
            else:
                sequence_lengths = -1

        pooled_logits = logits[
            torch.arange(batch_size, device=logits.device), sequence_lengths
        ]

        loss = None
        if labels is not None:
            labels = labels.to(logits.device)
            if self.config.problem_type is None:
                if self.num_labels == 1:
                    self.config.problem_type = "regression"
                elif self.num_labels > 1 and (
                    labels.dtype == torch.long or labels.dtype == torch.int
                ):
                    self.config.problem_type = "single_label_classification"
                else:
                    self.config.problem_type = "multi_label_classification"

            if self.config.problem_type == "regression":
                loss_fct = MSELoss()
                if self.num_labels == 1:
                    loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
                else:
                    loss = loss_fct(pooled_logits, labels)
            elif self.config.problem_type == "single_label_classification":
                loss_fct = CrossEntropyLoss()
                loss = loss_fct(
                    pooled_logits.view(-1, self.num_labels), labels.view(-1)
                )
            elif self.config.problem_type == "multi_label_classification":
                loss_fct = BCEWithLogitsLoss()
                loss = loss_fct(pooled_logits, labels)
        if not return_dict:
            output = (pooled_logits,) + transformer_outputs[1:]
            return ((loss,) + output) if loss is not None else output

        return SequenceClassifierOutputWithPast(
            loss=loss,
            logits=pooled_logits,
            past_key_values=transformer_outputs.past_key_values,
            hidden_states=transformer_outputs.hidden_states,
            attentions=transformer_outputs.attentions,
        )


# Backward-compatible aliases (only top-level wrappers keep the EkaV1 prefix).
# EkaV1RMSNorm = RMSNorm
# EkaV1RotaryEmbedding = RotaryEmbedding
# Ekav1LinearScalingRotaryEmbedding = LinearScalingRotaryEmbedding
# EkaV1DynamicNTKScalingRotaryEmbedding = DynamicNTKScalingRotaryEmbedding
# EkaV1YarnRotaryEmbedding = YarnRotaryEmbedding
# EkaV1FlashAttention2 = FlashAttention2
# EkaV1MambaDecoderLayer = MambaLayer
# EkaV1MoEOnlyDecoderLayer = MoETransformerLayer
# EkaV1DecoderLayer = TransformerLayer
# EkaV1MambaMixer = MambaMixer
# EkaV1MoE = MoELayer
# EkaV1MLP = MLP
# EkaV1MTP = MultiTokenPredictionBlock
# EkaV1MTPLayer = MultiTokenPredictionLayer
# EkaV1MTPTransformerLayer = TransformerLayer