Text Generation
Transformers
Safetensors
domynedge
domyn
domyn-edge
teacher
math
grpo
fully-open
conversational
custom_code
Run this model with HF Jobs
Run domyn/Domyn-Edge-Teacher-Math 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/domyn/Domyn-Edge-Teacher-Math. 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/domyn/Domyn-Edge-Teacher-Math 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/domyn/Domyn-Edge-Teacher-Math. 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.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/domyn/Domyn-Edge-Teacher-Math. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use domyn/Domyn-Edge-Teacher-Math with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use domyn/Domyn-Edge-Teacher-Math with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="domyn/Domyn-Edge-Teacher-Math", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("domyn/Domyn-Edge-Teacher-Math", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use domyn/Domyn-Edge-Teacher-Math with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "domyn/Domyn-Edge-Teacher-Math" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "domyn/Domyn-Edge-Teacher-Math", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/domyn/Domyn-Edge-Teacher-Math
- SGLang
How to use domyn/Domyn-Edge-Teacher-Math with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "domyn/Domyn-Edge-Teacher-Math" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "domyn/Domyn-Edge-Teacher-Math", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "domyn/Domyn-Edge-Teacher-Math" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "domyn/Domyn-Edge-Teacher-Math", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use domyn/Domyn-Edge-Teacher-Math with Docker Model Runner:
docker model run hf.co/domyn/Domyn-Edge-Teacher-Math
Commit ·
137fb7f
0
Parent(s):
Domyn Edge Teacher Math
Browse filesCo-authored-by: llmartin <llmartin@users.noreply.huggingface.co>
Files changed (13)
- .gitattributesAdded+36
- README.mdAdded+172
- __init__.pyAdded
- chat_template.jinjaAdded+159
- config.jsonAdded+291
- configuration_domynedge.pyAdded+141
- generation_config.jsonAdded+9
- model-00001-of-00001.safetensorsAdded+3
- model.safetensors.index.jsonAdded+441
- modeling_domynedge.pyAdded+473
- special_tokens_map.jsonAdded+46
- tokenizer.jsonAdded+3
- tokenizer_config.jsonAdded+144
123456789101112131415161718192021222324252627282930313233343536*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -texttokenizer.json filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172---library_name: transformerslicense: apache-2.0pipeline_tag: text-generationbase_model: domyn/Domyn-Edge-SFTdatasets: - domyn/Domyn-Edge-Teacher-Math-Mixlanguage: - en - it - es - fr - de - pt - ru - zh - ja - ar - nl - id - trtags: - domyn - domyn-edge - teacher - math - grpo - fully-open---
<p align="center"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://cdn.prod.website-files.com/682dcb35e7fd7a313cae803a/6835cb0fb6bd22a7cba7d645_domyn-logo-payoff-primary-white.svg"> <img alt="Domyn" src="https://cdn.prod.website-files.com/682dcb35e7fd7a313cae803a/6835ca86622d317630fa3861_domyn-logo-primary.svg" width="400"> </picture></p>
# Domyn Edge Teacher Math
> [!IMPORTANT]> **Phased release.** Domyn Edge is a rolling release in three bundles. This teacher is part of the> second bundle, together with the other domain teachers and their post-training data. See> [Open resources](#open-resources) for everything released so far.
> [!Note]> This repository holds the **math teacher** of Domyn Edge: Domyn Edge SFT after GRPO on math> problems with verifiable final answers. It is one of the domain teachers that score the student's> rollouts token by token in the multi-teacher on-policy distillation (MOPD) stage of our> post-training protocol. It is released for research and reproducibility; it is not a> general-purpose assistant.
## Table of contents
1. [Model summary](#model-summary)2. [How to use](#how-to-use)3. [Evaluation](#evaluation)4. [Limitations](#limitations)5. [Open resources](#open-resources)6. [License](#license)7. [Citation](#citation)
## Model summary
Domyn Edge Teacher Math is a 4B-parameter dense transformer with the same architecture and tokenizeras [Domyn Edge SFT](https://huggingface.co/domyn/Domyn-Edge-SFT). It was trained in one stage on topof Domyn Edge SFT:
- **GRPO**: asynchronous group relative policy optimization on math problems with a single verifiable final answer. The reward checks the final answer with [math-verify](https://github.com/huggingface/Math-Verify): 1 for a correct answer, 0.5 for a correct answer not given in the format the prompt asks for, 0 otherwise.
The weights are stored in bfloat16.
## How to use
The model loads and serves exactly like Domyn Edge SFT; see the[Domyn Edge SFT card](https://huggingface.co/domyn/Domyn-Edge-SFT#how-to-use) for the recommendedenvironment, Transformers and vLLM instructions.
**Chat template.** The repository ships the Domyn Edge SFT chat template unchanged; it is thetemplate used during GRPO training and in the evaluation below. It opens the system turn with afixed identity line ("You are Domyn Edge, a model trained by Domyn.").
**Output format.** The model reasons first and ends with the final answer, usually in `\boxed{}`.
## Evaluation
### Teacher vs student on the general evaluation suite
Scores of this teacher next to those of the student, [Domyn EdgeSFT](https://huggingface.co/domyn/Domyn-Edge-SFT), with one benchmark per area, to check what theteacher keeps outside its training domain. All scores are percentages.
| Group | Benchmark | Metric | Domyn Edge SFT | Teacher Math | Δ ||---|---|---|---:|---:|---:|| Math | AIME 2026 | avg@10 | 61.3 | **79.0** | +17.7 || Multilingual math | MGSM (de, en, es, fr, ru) | accuracy | 85.8 | **87.4** | +1.6 || Knowledge and reasoning | GPQA Diamond | pass@1 | 56.3 | **59.6** | +3.3 || Instruction following | IFBench | prompt strict pass@1 | 24.1 | **25.0** | +0.9 || Function calling | BFCL v4, without web search (overall) | pass@1 | **36.5** | 36.2 | -0.3 || | BFCL v4 (non-live) | pass@1 | 51.9 | **53.3** | +1.4 || | BFCL v4 (live) | pass@1 | **75.9** | 75.1 | -0.8 || | BFCL v4 (multi-turn) | pass@1 | 35.9 | **38.8** | +2.9 || | BFCL v4 (memory) | pass@1 | **27.3** | 21.5 | -5.8 || Agentic | SWE-bench Verified | pass@1 | **33.6** | 29.6 | -4.0 || Code | LiveCodeBench (full set)\* | pass@1 | **73.0** | 72.0 | -1.0 |
_\*LiveCodeBench (full set) is all 1,055 problems of LiveCodeBench v6, released between May 2023 andApril 2025._
<details><summary>Evaluation settings</summary>
- Served with vLLM in bfloat16, with the chat template shipped in this repository.- Thinking on. Sampling: temperature 1.0, top-p 0.95, top-k 20, min-p 0, no presence or repetition penalty.</details>
### Math evaluation suite
| Benchmark | Metric | Teacher Math | Qwen3.5 4B | Δ ||---|---|---:|---:|---:|| AIME 2026 | avg@10 | 79.0 | **82.9** | -3.9 || AIME 2025 | avg@10 | 75.9 | **78.3** | -2.4 || HMMT Feb 2026 | avg@10 | **65.9** | 63.3 | +2.6 || HMMT Feb 2025 | avg@10 | **76.1** | 74.6 | +1.5 || GSM8K | accuracy | 93.8 | **95.0** | -1.2 || MGSM (de, en, es, fr, ru) | accuracy | 87.4 | **89.8** | -2.4 |
<details><summary>Evaluation settings</summary>
- Served with vLLM in bfloat16 at 128k context, thinking on.- Sampling: temperature 1.0, top-p 0.95, top-k 20, min-p 0, no presence, frequency or repetition penalty.- AIME and HMMT: 10 samples per problem, accuracy averaged over the samples (avg@10).
</details>
## Limitations
**A teacher, not an assistant.** This model is one of the domain teachers of multi-teacher on-policydistillation (MOPD), the post-training stage in which the Domyn Edge student generates its ownresponses and each teacher scores them token by token in its own domain. Only math was trainedbeyond Domyn Edge SFT.
**Long generations.** On hard problems the model can reason for tens of thousands of tokens.Training capped responses at 64k tokens; cap the generation length.
**Safety work is incomplete.** No dedicated safety tuning or red teaming was done on this model.
## Open resources
- **This teacher**: [`domyn/Domyn-Edge-Teacher-Math`](https://huggingface.co/domyn/Domyn-Edge-Teacher-Math)- **Its data**: [`domyn/Domyn-Edge-Teacher-Math-Mix`](https://huggingface.co/datasets/domyn/Domyn-Edge-Teacher-Math-Mix)- **Student SFT model**: [`domyn/Domyn-Edge-SFT`](https://huggingface.co/domyn/Domyn-Edge-SFT), and its mix [`domyn/Domyn-Edge-SFT-Mix`](https://huggingface.co/datasets/domyn/Domyn-Edge-SFT-Mix)- **Collection**: [Domyn Edge](https://huggingface.co/collections/domyn/domyn-edge) on Hugging Face
## License
This model is released under [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0).
## Citation
```bibtex@misc{domynedge2026, title = {Domyn Edge}, author = {Domyn}, year = {2026}, note = {Technical report, forthcoming in November 2026.},}```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159{%- set image_count = namespace(value=0) %}{%- set video_count = namespace(value=0) %}{%- macro render_content(content, do_vision_count, is_system_content=false) %} {%- if content is string %} {{- content }} {%- elif content is iterable and content is not mapping %} {%- for item in content %} {%- if 'image' in item or 'image_url' in item or item.type == 'image' %} {%- if is_system_content %} {{- raise_exception('System message cannot contain images.') }} {%- endif %} {%- if do_vision_count %} {%- set image_count.value = image_count.value + 1 %} {%- endif %} {%- if add_vision_id %} {{- 'Picture ' ~ image_count.value ~ ': ' }} {%- endif %} {{- '<|vision_start|><|image_pad|><|vision_end|>' }} {%- elif 'video' in item or item.type == 'video' %} {%- if is_system_content %} {{- raise_exception('System message cannot contain videos.') }} {%- endif %} {%- if do_vision_count %} {%- set video_count.value = video_count.value + 1 %} {%- endif %} {%- if add_vision_id %} {{- 'Video ' ~ video_count.value ~ ': ' }} {%- endif %} {{- '<|vision_start|><|video_pad|><|vision_end|>' }} {%- elif 'text' in item %} {{- item.text }} {%- else %} {{- raise_exception('Unexpected item type in content.') }} {%- endif %} {%- endfor %} {%- elif content is none or content is undefined %} {{- '' }} {%- else %} {{- raise_exception('Unexpected content type.') }} {%- endif %}{%- endmacro %}{%- if not messages %} {{- raise_exception('No messages provided.') }}{%- endif %}{%- set identity = 'You are Domyn Edge, a model trained by Domyn.' %}{%- if tools and tools is iterable and tools is not mapping %} {{- '<|im_start|>system\n' + identity + '\n\n' }} {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }} {%- for tool in tools %} {{- "\n" }} {{- tool | tojson }} {%- endfor %} {{- "\n</tools>" }} {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }} {%- if messages[0].role == 'system' %} {%- set content = render_content(messages[0].content, false, true)|trim %} {%- if content %} {{- '\n\n' + content }} {%- endif %} {%- endif %} {{- '<|im_end|>\n' }}{%- else %} {{- '<|im_start|>system\n' + identity }} {%- if messages[0].role == 'system' %} {%- set content = render_content(messages[0].content, false, true)|trim %} {%- if content %} {{- '\n\n' + content }} {%- endif %} {%- endif %} {{- '<|im_end|>\n' }}{%- endif %}{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}{%- for message in messages[::-1] %} {%- set index = (messages|length - 1) - loop.index0 %} {%- if ns.multi_step_tool and message.role == "user" %} {%- set content = render_content(message.content, false)|trim %} {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %} {%- set ns.multi_step_tool = false %} {%- set ns.last_query_index = index %} {%- endif %} {%- endif %}{%- endfor %}{%- if ns.multi_step_tool %} {{- raise_exception('No user query found in messages.') }}{%- endif %}{%- for message in messages %} {%- set content = render_content(message.content, true)|trim %} {%- if message.role == "system" %} {%- if not loop.first %} {{- raise_exception('System message must be at the beginning.') }} {%- endif %} {%- elif message.role == "user" %} {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} {%- elif message.role == "assistant" %} {%- set reasoning_content = '' %} {%- if message.reasoning_content is string %} {%- set reasoning_content = message.reasoning_content %} {%- else %} {%- if '</think>' in content %} {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %} {%- set content = content.split('</think>')[-1].lstrip('\n') %} {%- endif %} {%- endif %} {%- set reasoning_content = reasoning_content|trim %} {%- if (preserve_thinking is defined and preserve_thinking is true) or (loop.index0 > ns.last_query_index) %} {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }} {%- else %} {{- '<|im_start|>' + message.role + '\n' + content }} {%- endif %} {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %} {%- for tool_call in message.tool_calls %} {%- if tool_call.function is defined %} {%- set tool_call = tool_call.function %} {%- endif %} {%- if loop.first %} {%- if content|trim %} {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }} {%- else %} {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }} {%- endif %} {%- else %} {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }} {%- endif %} {%- if tool_call.arguments is defined %} {%- for args_name, args_value in tool_call.arguments|items %} {{- '<parameter=' + args_name + '>\n' }} {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %} {{- args_value }} {{- '\n</parameter>\n' }} {%- endfor %} {%- endif %} {{- '</function>\n</tool_call>' }} {%- endfor %} {%- endif %} {{- '<|im_end|>\n' }} {%- elif message.role == "tool" %} {%- if loop.previtem and loop.previtem.role != "tool" %} {{- '<|im_start|>user' }} {%- endif %} {{- '\n<tool_response>\n' }} {{- content }} {{- '\n</tool_response>' }} {%- if not loop.last and loop.nextitem.role != "tool" %} {{- '<|im_end|>\n' }} {%- elif loop.last %} {{- '<|im_end|>\n' }} {%- endif %} {%- else %} {{- raise_exception('Unexpected message role.') }} {%- endif %}{%- endfor %}{%- if add_generation_prompt %} {{- '<|im_start|>assistant\n' }} {%- if enable_thinking is defined and enable_thinking is false %} {{- '<think>\n\n</think>\n\n' }} {%- else %} {{- '<think>\n' }} {%- endif %}{%- endif %}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291{ "architectures": [ "DomynEdgeForCausalLM" ], "attention_dropout": 0.0, "auto_map": { "AutoConfig": "configuration_domynedge.DomynEdgeConfig", "AutoModel": "modeling_domynedge.DomynEdgeModel", "AutoModelForCausalLM": "modeling_domynedge.DomynEdgeForCausalLM" }, "dtype": "bfloat16", "hidden_act": "silu", "hidden_size": 2560, "initializer_range": 0.02, "intermediate_size": 9728, "max_position_embeddings": 262144, "model_type": "domynedge", "num_attention_heads": 32, "num_hidden_layers": 36, "num_key_value_heads": 8, "rms_norm_eps": 1e-06, "position_layers": [ "nope", "nope", "rope", "rope", "rope", "nope", "rope", "rope", "rope", "nope", "rope", "rope", "rope", "nope", "rope", "rope", "rope", "nope", "rope", "rope", "rope", "nope", "rope", "rope", "rope", "nope", "rope", "rope", "rope", "nope", "rope", "rope", "rope", "nope", "nope", "nope" ], "window_sizes": [ [ -1, 0 ], [ -1, 0 ], [ 1024, 0 ], [ 1024, 0 ], [ 1024, 0 ], [ -1, 0 ], [ 1024, 0 ], [ 1024, 0 ], [ 1024, 0 ], [ -1, 0 ], [ 1024, 0 ], [ 1024, 0 ], [ 1024, 0 ], [ -1, 0 ], [ 1024, 0 ], [ 1024, 0 ], [ 1024, 0 ], [ -1, 0 ], [ 1024, 0 ], [ 1024, 0 ], [ 1024, 0 ], [ -1, 0 ], [ 1024, 0 ], [ 1024, 0 ], [ 1024, 0 ], [ -1, 0 ], [ 1024, 0 ], [ 1024, 0 ], [ 1024, 0 ], [ -1, 0 ], [ 1024, 0 ], [ 1024, 0 ], [ 1024, 0 ], [ -1, 0 ], [ -1, 0 ], [ -1, 0 ] ], "layer_types": [ "full_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "full_attention", "full_attention" ], "sliding_window": 1025, "head_sizes": [ 256, 256, 64, 64, 64, 256, 64, 64, 64, 256, 64, 64, 64, 256, 64, 64, 64, 256, 64, 64, 64, 256, 64, 64, 64, 256, 64, 64, 64, 256, 64, 64, 64, 256, 256, 256 ], "tie_word_embeddings": true, "rope_parameters": { "rope_type": "default", "rope_theta": 10000.0 }, "transformers_version": "5.8.1", "use_cache": true, "vocab_size": 115272}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141# SPDX-FileCopyrightText: 2026 Domyn# SPDX-License-Identifier: Apache-2.0
import typing
from transformers.configuration_utils import PreTrainedConfigfrom transformers.modeling_rope_utils import RopeParameters
class DomynEdgeConfig(PreTrainedConfig): """Configuration of a DomynEdge model, with per-layer position encoding, sliding window and head size."""
model_type: typing.ClassVar[str] = "domynedge" default_theta: float = 10_000
def __init__( self, vocab_size: int = 115269, hidden_size: int = 2560, intermediate_size: int = 9728, num_hidden_layers: int = 36, num_attention_heads: int = 32, num_key_value_heads: int = 8, max_position_embeddings: int = 8192, initializer_range: float = 0.02, rms_norm_eps: float = 1e-6, *, use_cache: bool = True, tie_word_embeddings: bool = True, rope_parameters: RopeParameters | None = None, max_window_layers: int | None = None, attention_bias: bool = False, attention_dropout: float = 0.0, position_layers: list[str] = ["nope", "nope"] + ["rope", "rope", "rope", "nope"] * 8 + ["nope", "nope"], layer_types: list[str] = ["full_attention", "full_attention"] + ["sliding_attention", "sliding_attention", "sliding_attention", "full_attention"] * 8 + ["full_attention", "full_attention"], sliding_window: int | None = 1025, head_sizes: list[int] = [256, 256] + [64, 64, 64, 256] * 8 + [256, 256], pad_token_id: int | None = None, bos_token_id: int | None = None, eos_token_id: int | None = None, **kwargs, ): """Initialize and validate the per-layer settings, which must all have `num_hidden_layers` entries.""" self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads # TODO: remove once vLLM's native DomynEdge no longer requires it. It was used by Qwen2 `max_window_layers` # but in Domyn Edge `layer_types` alone decides which layers slide. self.max_window_layers = num_hidden_layers if max_window_layers is None else max_window_layers
# for backward compatibility if num_key_value_heads is None: num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads self.initializer_range = initializer_range self.rms_norm_eps = rms_norm_eps self.use_cache = use_cache self.attention_bias = attention_bias self.attention_dropout = attention_dropout
self.position_layers = position_layers self.layer_types = layer_types self.sliding_window = sliding_window self.head_sizes = head_sizes
# Validate position_layers if len(self.position_layers) != self.num_hidden_layers: msg = ( f"Length of position_layers ({len(self.position_layers)}) " f"must be equal to num_hidden_layers ({self.num_hidden_layers})" ) raise ValueError(msg) if any(pl not in ["rope", "nope"] for pl in self.position_layers): msg = f"position_layers must be one of 'rope', 'nope'. Got {self.position_layers}" raise ValueError(msg) # Validate layer_types and sliding_window if len(self.layer_types) != self.num_hidden_layers: msg = ( f"Length of layer_types ({len(self.layer_types)}) " f"must be equal to num_hidden_layers ({self.num_hidden_layers})" ) raise ValueError(msg) if "sliding_attention" in self.layer_types and self.sliding_window is None: msg = "sliding_window must be set when layer_types contains 'sliding_attention'" raise ValueError(msg) # Validate head_sizes if len(head_sizes) != self.num_hidden_layers: msg = ( f"Length of head_sizes ({len(head_sizes)}) " f"must be equal to num_hidden_layers ({self.num_hidden_layers})" ) raise ValueError(msg) if any(not isinstance(hs, int) for hs in head_sizes): msg = f"head_sizes must be a list of integers. Got {head_sizes}" raise ValueError(msg) # Only one rope dim rope_dims = [head_size for rope, head_size in zip(position_layers, head_sizes, strict=True) if rope == "rope"] if len(set(rope_dims)) > 1: msg = f"All rope layers must have the same head size. Got {rope_dims}" raise ValueError(msg)
kwargs.pop("rope_dim", None) # derived from rope_dims, never read from config.json. It won't be passed to super kwargs.pop("window_sizes", None) # derived from layer_types, see the `window_sizes` property self.rope_dim = rope_dims[0]
# If None, `super().__init__` calls `RotaryEmbeddingConfigMixin.convert_rope_params_to_dict`, which builds # `{"rope_type": "default", "rope_theta": ...}` with the legacy top-level `rope_theta` kwarg if present, # else `default_theta`. self.rope_parameters = rope_parameters
self.pad_token_id = pad_token_id self.bos_token_id = bos_token_id self.eos_token_id = eos_token_id self.tie_word_embeddings = tie_word_embeddings
if "per_layer_config" not in kwargs: kwargs["per_layer_config"] = { layer_idx: {"head_dim": head_size} for layer_idx, head_size in enumerate(head_sizes) }
super().__init__(**kwargs)
@property def window_sizes(self) -> list[tuple[int, int]]: """The torchtitan (left, right) attention window of each layer, (-1, 0) for full attention.
Legacy implementation to be compatible with vLLM v0.33, to be removed when updated from vLLM side. """ return [ (self.sliding_window - 1, 0) if layer_type == "sliding_attention" and self.sliding_window else (-1, 0) for layer_type in self.layer_types ]
__all__ = ["DomynEdgeConfig"]123456789{ "bos_token_id": 115258, "do_sample": true, "eos_token_id": 115259, "pad_token_id": 115268, "temperature": 1.0, "top_k": 20, "top_p": 0.95}123version https://git-lfs.github.com/spec/v1oid sha256:c2936b785d425136fee84e74e8032d9638b4208f7bc2531e0616816160a032d9size 7857626952123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441{ "metadata": { "total_size": 7857575936 }, "weight_map": { "model.embed_tokens.weight": "model-00001-of-00001.safetensors", "model.layers.0.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.0.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.0.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.0.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.0.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.0.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.0.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.0.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.0.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.0.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.0.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.0.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.1.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.1.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.1.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.1.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.1.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.1.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.1.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.1.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.1.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.1.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.1.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.1.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.10.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.10.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.10.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.10.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.10.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.10.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.10.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.10.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.10.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.10.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.10.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.10.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.11.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.11.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.11.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.11.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.11.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.11.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.11.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.11.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.11.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.11.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.11.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.11.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.12.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.12.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.12.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.12.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.12.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.12.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.12.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.12.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.12.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.12.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.12.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.12.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.13.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.13.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.13.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.13.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.13.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.13.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.13.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.13.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.13.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.13.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.13.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.13.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.14.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.14.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.14.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.14.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.14.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.14.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.14.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.14.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.14.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.14.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.14.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.14.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.15.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.15.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.15.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.15.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.15.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.15.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.15.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.15.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.15.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.15.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.15.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.15.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.16.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.16.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.16.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.16.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.16.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.16.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.16.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.16.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.16.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.16.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.16.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.16.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.17.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.17.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.17.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.17.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.17.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.17.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.17.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.17.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.17.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.17.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.17.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.17.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.18.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.18.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.18.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.18.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.18.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.18.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.18.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.18.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.18.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.18.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.18.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.18.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.19.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.19.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.19.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.19.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.19.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.19.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.19.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.19.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.19.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.19.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.19.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.19.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.2.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.2.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.2.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.2.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.2.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.2.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.2.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.2.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.2.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.2.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.2.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.2.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.20.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.20.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.20.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.20.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.20.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.20.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.20.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.20.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.20.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.20.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.20.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.20.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.21.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.21.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.21.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.21.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.21.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.21.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.21.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.21.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.21.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.21.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.21.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.21.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.22.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.22.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.22.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.22.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.22.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.22.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.22.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.22.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.22.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.22.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.22.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.22.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.23.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.23.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.23.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.23.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.23.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.23.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.23.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.23.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.23.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.23.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.23.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.23.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.24.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.24.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.24.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.24.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.24.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.24.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.24.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.24.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.24.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.24.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.24.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.24.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.25.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.25.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.25.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.25.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.25.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.25.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.25.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.25.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.25.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.25.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.25.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.25.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.26.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.26.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.26.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.26.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.26.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.26.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.26.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.26.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.26.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.26.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.26.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.26.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.27.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.27.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.27.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.27.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.27.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.27.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.27.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.27.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.27.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.27.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.27.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.27.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.28.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.28.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.28.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.28.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.28.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.28.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.28.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.28.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.28.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.28.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.28.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.28.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.29.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.29.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.29.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.29.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.29.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.29.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.29.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.29.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.29.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.29.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.29.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.29.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.3.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.3.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.3.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.3.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.3.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.3.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.3.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.3.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.3.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.3.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.3.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.3.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.30.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.30.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.30.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.30.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.30.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.30.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.30.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.30.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.30.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.30.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.30.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.30.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.31.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.31.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.31.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.31.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.31.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.31.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.31.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.31.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.31.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.31.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.31.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.31.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.32.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.32.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.32.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.32.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.32.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.32.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.32.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.32.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.32.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.32.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.32.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.32.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.33.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.33.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.33.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.33.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.33.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.33.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.33.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.33.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.33.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.33.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.33.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.33.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.34.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.34.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.34.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.34.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.34.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.34.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.34.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.34.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.34.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.34.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.34.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.34.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.35.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.35.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.35.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.35.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.35.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.35.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.35.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.35.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.35.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.35.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.35.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.35.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.4.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.4.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.4.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.4.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.4.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.4.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.4.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.4.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.4.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.4.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.4.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.4.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.5.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.5.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.5.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.5.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.5.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.5.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.5.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.5.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.5.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.5.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.5.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.5.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.6.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.6.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.6.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.6.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.6.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.6.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.6.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.6.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.6.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.6.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.6.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.6.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.7.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.7.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.7.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.7.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.7.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.7.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.7.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.7.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.7.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.7.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.7.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.7.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.8.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.8.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.8.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.8.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.8.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.8.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.8.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.8.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.8.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.8.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.8.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.8.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.9.attention.k_norm.weight": "model-00001-of-00001.safetensors", "model.layers.9.attention.k_proj.weight": "model-00001-of-00001.safetensors", "model.layers.9.attention.o_proj.weight": "model-00001-of-00001.safetensors", "model.layers.9.attention.q_proj.weight": "model-00001-of-00001.safetensors", "model.layers.9.attention.v_proj.weight": "model-00001-of-00001.safetensors", "model.layers.9.feedforward.down_proj.weight": "model-00001-of-00001.safetensors", "model.layers.9.feedforward.gate_proj.weight": "model-00001-of-00001.safetensors", "model.layers.9.feedforward.up_proj.weight": "model-00001-of-00001.safetensors", "model.layers.9.post_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.9.post_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.layers.9.pre_attention_norm.weight": "model-00001-of-00001.safetensors", "model.layers.9.pre_feedforward_norm.weight": "model-00001-of-00001.safetensors", "model.norm.weight": "model-00001-of-00001.safetensors" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473# SPDX-FileCopyrightText: 2026 Domyn# SPDX-License-Identifier: Apache-2.0## This file includes third-party code:## - `DomynEdgeRotaryEmbedding.compute_default_rope_parameters` and `apply_rotary_pos_emb` are adapted from# HuggingFace transformers# (https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py),# Copyright The HuggingFace Team, licensed under the Apache License, Version 2.0.# Modified for DomynEdge.
import typing
import torchimport torch.nn.attention.varlenimport transformersimport transformers.modeling_outputsfrom transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask, flash_attention_maskfrom transformers.modeling_flash_attention_utils import ( _is_packed_sequence, _pad_input, _prepare_from_posids, _unpad_input, _upad_input,)from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONSfrom transformers.models.llama.modeling_llama import eager_attention_forward, rotate_halffrom transformers.utils.generic import can_return_tuple, merge_with_config_defaultsfrom transformers.utils.output_capturing import capture_outputs
from .configuration_domynedge import DomynEdgeConfig
class DomynEdgeFeedForward(torch.nn.Module): def __init__(self, config): super().__init__() self.config = config self.hidden_size = config.hidden_size self.intermediate_size = config.intermediate_size self.gate_proj = torch.nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self.up_proj = torch.nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self.down_proj = torch.nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
def forward(self, x): return self.down_proj(torch.nn.functional.silu(self.gate_proj(x)) * self.up_proj(x))
class DomynEdgeRotaryEmbedding(torch.nn.Module): inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: DomynEdgeConfig, device=None): super().__init__() self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings
self.config = config
assert self.config.rope_parameters is not None self.rope_type = self.config.rope_parameters["rope_type"] rope_init_fn: typing.Callable = self.compute_default_rope_parameters inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
self.register_buffer("inv_freq", inv_freq, persistent=False) self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
@staticmethod def compute_default_rope_parameters( config: DomynEdgeConfig, device: typing.Optional["torch.device"] = None, ) -> tuple["torch.Tensor", float]: """Computes the inverse frequencies according to the original RoPE implementation.
Args: config ([`~transformers.PreTrainedConfig`]): The model configuration. device (`torch.device`): The device to use for initialization of the inverse frequencies.
Returns: Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). """ assert config.rope_parameters is not None assert config.rope_parameters["rope_theta"] is not None
base = config.rope_parameters["rope_theta"] dim = config.rope_dim
attention_factor = 1.0 # Unused in this type of RoPE
# Compute the inverse frequencies inv_freq = 1.0 / ( base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim) ) return inv_freq, attention_factor
@torch.no_grad() def forward(self, x, position_ids): # Recomputed on the input's device instead of reading the `inv_freq` buffer, to match the training # implementation. inv_freq, _ = self.compute_default_rope_parameters(self.config, x.device) # An elementwise product, not a matmul, so torch.autocast(bfloat16) does not lower it. freqs = position_ids[..., None].float() * inv_freq emb = torch.cat((freqs, freqs), dim=-1) cos = emb.cos() * self.attention_scaling sin = emb.sin() * self.attention_scaling
return cos, sin
def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1): """Applies Rotary Position Embedding to the query and key tensors.
Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. unsqueeze_dim (`int`, *optional*, defaults to 1): The dimension along which to unsqueeze cos and sin so that they broadcast to q and k. Use 1 when q and k have the shape [batch_size, heads, seq_len, head_dim], 2 for [batch_size, seq_len, heads, head_dim].
Returns: `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. """ cos = cos.unsqueeze(unsqueeze_dim) sin = sin.unsqueeze(unsqueeze_dim) qf, kf = q.float(), k.float() q_embed = (qf * cos) + (rotate_half(qf) * sin) k_embed = (kf * cos) + (rotate_half(kf) * sin) # Main difference with respect to transformers.models.llama.modeling_llama, llama does not do the upcast return q_embed.to(q.dtype), k_embed.to(k.dtype)
def torch_varlen_attention_forward( _module: torch.nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: torch.Tensor | None, scaling: float | None = None, sliding_window: int | None = None, position_ids: torch.Tensor | None = None, **_kwargs,) -> tuple[torch.Tensor, None]: """Attention through PyTorch's built-in flash kernel, the one the model is trained with.
Selected with `attn_implementation="torch_varlen"`, it needs no `flash_attn` package. """ batch_size, _, q_len, head_dim = query.shape query, key, value = query.transpose(1, 2), key.transpose(1, 2), value.transpose(1, 2) indices_q = None if attention_mask is not None: query, key, value, indices_q, (cu_seq_q, cu_seq_k), (max_q, max_k) = _upad_input( query, key, value, attention_mask, q_len, _unpad_input ) elif _is_packed_sequence(position_ids, batch_size): query, key, value, (cu_seq_q, cu_seq_k), (max_q, max_k) = _prepare_from_posids(query, key, value, position_ids) max_q, max_k = int(max_q), int(max_k) else: k_len = key.shape[1] query, key, value = query.flatten(0, 1), key.flatten(0, 1), value.flatten(0, 1) cu_seq_q = torch.arange(0, (batch_size + 1) * q_len, q_len, dtype=torch.int32, device=query.device) cu_seq_k = torch.arange(0, (batch_size + 1) * k_len, k_len, dtype=torch.int32, device=query.device) max_q, max_k = q_len, k_len
output = torch.nn.attention.varlen.varlen_attn( query, key, value, cu_seq_q, cu_seq_k, max_q, max_k, scale=scaling, # transformers' `sliding_window` counts the current token, flash attention's left window does not. window_size=(-1 if sliding_window is None else sliding_window - 1, 0), enable_gqa=query.shape[1] != key.shape[1], ) assert isinstance(output, torch.Tensor) if indices_q is None: return output.view(batch_size, q_len, -1, head_dim), None return _pad_input(output, indices_q, batch_size, q_len), None
transformers.AttentionInterface.register("torch_varlen", torch_varlen_attention_forward)# Without a registered mask function, transformers passes no mask at all to a custom implementation, padding included.transformers.AttentionMaskInterface.register("torch_varlen", flash_attention_mask)
class DomynEdgeAttention(torch.nn.Module): """Grouped Query Attention with per-layer head size, optional RoPE and optional sliding window.
Attention is dispatched through `ALL_ATTENTION_FUNCTIONS`, so any transformers attention implementation (eager, sdpa, flash_attention_2, flex) and vLLM's Transformers backend can serve it. """
def __init__(self, config: DomynEdgeConfig, layer_idx: int): super().__init__() self.config = config self.layer_idx = layer_idx self.layer_type = config.layer_types[layer_idx] self.head_dim = config.per_layer_config[layer_idx].head_dim self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads self.scaling = self.head_dim**-0.5 self.attention_dropout = config.attention_dropout self.is_causal = True self.use_rope = config.position_layers[layer_idx] == "rope" self.sliding_window = config.sliding_window if self.layer_type == "sliding_attention" else None
self.q_proj = torch.nn.Linear( config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias ) self.k_proj = torch.nn.Linear( config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias ) self.v_proj = torch.nn.Linear( config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias ) self.o_proj = torch.nn.Linear( config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias ) self.q_norm = torch.nn.RMSNorm(self.head_dim, eps=config.rms_norm_eps, elementwise_affine=False) self.k_norm = torch.nn.RMSNorm(self.head_dim, eps=config.rms_norm_eps, elementwise_affine=True)
def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], attention_mask: torch.Tensor | None, past_key_values: transformers.Cache | None = None, **kwargs, ) -> tuple[torch.Tensor, torch.Tensor | None]: batch_size, sequence_length, _ = hidden_states.shape query_shape = (batch_size, sequence_length, self.config.num_attention_heads, self.head_dim) key_value_shape = (batch_size, sequence_length, self.config.num_key_value_heads, self.head_dim)
query_states = self.q_norm(self.q_proj(hidden_states).view(query_shape)).transpose(1, 2) key_states = self.k_norm(self.k_proj(hidden_states).view(key_value_shape)).transpose(1, 2) value_states = self.v_proj(hidden_states).view(key_value_shape).transpose(1, 2)
if self.use_rope: cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
if past_key_values is not None: key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
# `get_interface` handles a None implementation, despite its `str` annotation attention_interface: typing.Callable = ALL_ATTENTION_FUNCTIONS.get_interface( self.config._attn_implementation, # noqa: SLF001 # pyright: ignore[reportArgumentType] eager_attention_forward, )
attn_output, attn_weights = attention_interface( self, query_states, key_states, value_states, attention_mask, dropout=0.0 if not self.training else self.attention_dropout, scaling=self.scaling, sliding_window=self.sliding_window, **kwargs, )
attn_output = attn_output.reshape( batch_size, sequence_length, self.config.num_attention_heads * self.head_dim ).contiguous() attn_output = self.o_proj(attn_output) return attn_output, attn_weights
class DomynEdgeDecoderLayer(torch.nn.Module): def __init__(self, config: DomynEdgeConfig, layer_idx: int): super().__init__() self.config = config
self.attention = DomynEdgeAttention(config=config, layer_idx=layer_idx) self.feedforward = DomynEdgeFeedForward(config)
self.pre_attention_norm = torch.nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.pre_feedforward_norm = torch.nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_norm = torch.nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_feedforward_norm = torch.nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor | None = None, past_key_values: transformers.Cache | None = None, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, **kwargs, ) -> torch.Tensor: # Self Attention attn_output, _ = self.attention( hidden_states=self.pre_attention_norm(hidden_states), attention_mask=attention_mask, past_key_values=past_key_values, position_embeddings=position_embeddings, **kwargs, ) hidden_states = hidden_states + self.post_attention_norm(attn_output)
## Fully Connected return hidden_states + self.post_feedforward_norm(self.feedforward(self.pre_feedforward_norm(hidden_states)))
class DomynEdgePreTrainedModel(transformers.PreTrainedModel): """Base class wiring DomynEdge into the HuggingFace `PreTrainedModel` machinery."""
config: DomynEdgeConfig base_model_prefix = "model" supports_gradient_checkpointing = False _no_split_modules = ["DomynEdgeDecoderLayer"] _skip_keys_device_placement = ["past_key_values"] _supports_flash_attn = True _supports_sdpa = True _supports_flex_attn = True
_can_compile_fullgraph = True _supports_attention_backend = True _can_record_outputs = { "hidden_states": DomynEdgeDecoderLayer, "attentions": DomynEdgeAttention, }
class DomynEdgeModel(DomynEdgePreTrainedModel): """DomynEdge decoder stack without the language modeling head."""
def __init__(self, config: DomynEdgeConfig): """Build the embeddings, decoder layers, final norm and rotary embedding from `config`.""" super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size
self.embed_tokens = torch.nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) self.layers = torch.nn.ModuleList( [DomynEdgeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.norm = torch.nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.rotary_emb = DomynEdgeRotaryEmbedding(config=config) self.has_sliding_layers = "sliding_attention" in config.layer_types
# Initialize weights and apply final processing self.post_init()
@merge_with_config_defaults @capture_outputs def forward( self, input_ids: torch.LongTensor | None = None, attention_mask: torch.Tensor | dict[str, torch.Tensor] | None = None, past_key_values: transformers.Cache | None = None, inputs_embeds: torch.Tensor | None = None, position_ids: torch.Tensor | None = None, use_cache: bool | None = None, **kwargs, ) -> transformers.modeling_outputs.BaseModelOutputWithPast: """Run the decoder stack and return the final hidden states (and the cache when `use_cache` is set).""" if (input_ids is None) ^ (inputs_embeds is not None): msg = "You must specify exactly one of input_ids or inputs_embeds" raise ValueError(msg)
if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids) assert inputs_embeds is not None
if use_cache and past_key_values is None: past_key_values = transformers.DynamicCache(config=self.config)
if position_ids is None: past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens position_ids = position_ids.unsqueeze(0)
# It may already have been prepared by the caller, e.g. `generate` if not isinstance(causal_mask_mapping := attention_mask, dict): mask_kwargs = { "config": self.config, "inputs_embeds": inputs_embeds, "attention_mask": attention_mask, "past_key_values": past_key_values, "position_ids": position_ids, } causal_mask_mapping = {"full_attention": create_causal_mask(**mask_kwargs)} if self.has_sliding_layers: causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
hidden_states = inputs_embeds position_embeddings = self.rotary_emb(hidden_states, position_ids)
for i, decoder_layer in enumerate(self.layers): hidden_states = decoder_layer( hidden_states, attention_mask=causal_mask_mapping[self.config.layer_types[i]], position_embeddings=position_embeddings, position_ids=position_ids, past_key_values=past_key_values, **kwargs, )
hidden_states = self.norm(hidden_states) return transformers.modeling_outputs.BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=past_key_values if use_cache else None, )
class DomynEdgeForCausalLM(DomynEdgePreTrainedModel, transformers.GenerationMixin): """DomynEdge model with a language modeling head tied to the input embeddings."""
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
def __init__(self, config): """Build the decoder stack and the language modeling head from `config`.""" super().__init__(config) self.model = DomynEdgeModel(config) self.vocab_size = config.vocab_size self.lm_head = torch.nn.Linear(config.hidden_size, config.vocab_size, bias=False)
# Initialize weights and apply final processing self.post_init()
@can_return_tuple def forward( self, input_ids: torch.LongTensor | None = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: transformers.Cache | None = None, inputs_embeds: torch.FloatTensor | None = None, labels: torch.LongTensor | None = None, use_cache: bool | None = None, logits_to_keep: int | torch.Tensor = 0, **kwargs, ) -> transformers.modeling_outputs.CausalLMOutputWithPast: """Compute logits for the last `logits_to_keep` positions, plus the loss when `labels` are given.""" 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, **kwargs, )
hidden_states = outputs.last_hidden_state # Only compute necessary logits, and do not upcast them to float if we are not computing the loss slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :]) loss = ( self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs) if labels is not None else None )
return transformers.modeling_outputs.CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
__all__ = [ "DomynEdgeForCausalLM", "DomynEdgeModel", "DomynEdgePreTrainedModel",]12345678910111213141516171819202122232425262728293031323334353637383940414243444546{ "additional_special_tokens": [ { "content": "<|fim_prefix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, { "content": "<|fim_suffix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, { "content": "<|fim_middle|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false } ], "bos_token": { "content": "<|beginoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "eos_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "pad_token": { "content": "<|pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }}123version https://git-lfs.github.com/spec/v1oid sha256:b674b69c9a68226dc8ca2a88a161ee1fd917dafc0361c442f8ec3d4073e967d2size 15956463123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144{ "added_tokens_decoder": { "115256": { "content": "<|beginoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "115257": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "115258": { "content": "<|im_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "115259": { "content": "<|im_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "115260": { "content": "<tool_call>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "115261": { "content": "</tool_call>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "115262": { "content": "<repo_name>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "115263": { "content": "<file_sep>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "115264": { "content": "<tool_response>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "115265": { "content": "</tool_response>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "115266": { "content": "<think>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "115267": { "content": "</think>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "115268": { "content": "<|pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "115269": { "content": "<|fim_prefix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "115270": { "content": "<|fim_suffix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "115271": { "content": "<|fim_middle|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true } }, "additional_special_tokens": [ "<|fim_prefix|>", "<|fim_suffix|>", "<|fim_middle|>" ], "bos_token": "<|im_start|>", "clean_up_tokenization_spaces": false, "eos_token": "<|im_end|>", "extra_special_tokens": {}, "model_max_length": 1000000000000000019884624838656, "pad_token": "<|pad|>", "tokenizer_class": "PreTrainedTokenizerFast"}.gitattributesAdded+36
README.mdAdded+172
__init__.pyAdded
chat_template.jinjaAdded+159
config.jsonAdded+291
configuration_domynedge.pyAdded+141
generation_config.jsonAdded+9
model-00001-of-00001.safetensorsAdded+3
model.safetensors.index.jsonAdded+441
modeling_domynedge.pyAdded+473
special_tokens_map.jsonAdded+46
tokenizer.jsonAdded+3
tokenizer_config.jsonAdded+144