Run this model with HF Jobs
Run ukisai/Swift-Inkling-2-Mini-MLX-bf16 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 to fine-tune https://huggingface.co/ukisai/Swift-Inkling-2-Mini-MLX-bf16. 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/ukisai/Swift-Inkling-2-Mini-MLX-bf16 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/ukisai/Swift-Inkling-2-Mini-MLX-bf16. 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.
Instructions to use ukisai/Swift-Inkling-2-Mini-MLX-bf16 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use ukisai/Swift-Inkling-2-Mini-MLX-bf16 with MLX:
# Make sure mlx-vlm is installed # pip install --upgrade mlx-vlm from mlx_vlm import load, generate from mlx_vlm.prompt_utils import apply_chat_template from mlx_vlm.utils import load_config # Load the model model, processor = load("ukisai/Swift-Inkling-2-Mini-MLX-bf16") config = load_config("ukisai/Swift-Inkling-2-Mini-MLX-bf16") # Prepare input image = ["http://images.cocodataset.org/val2017/000000039769.jpg"] prompt = "Describe this image." # Apply chat template formatted_prompt = apply_chat_template( processor, config, prompt, num_images=1 ) # Generate output output = generate(model, processor, formatted_prompt, image) print(output) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- Pi
How to use ukisai/Swift-Inkling-2-Mini-MLX-bf16 with Pi:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "ukisai/Swift-Inkling-2-Mini-MLX-bf16"
Configure the model in Pi
# Install Pi: npm install -g @earendil-works/pi-coding-agent # Add to ~/.pi/agent/models.json: { "providers": { "mlx-lm": { "baseUrl": "http://localhost:8080/v1", "api": "openai-completions", "apiKey": "none", "models": [ { "id": "ukisai/Swift-Inkling-2-Mini-MLX-bf16" } ] } } }Run Pi
# Start Pi in your project directory: pi
- Hermes Agent
How to use ukisai/Swift-Inkling-2-Mini-MLX-bf16 with Hermes Agent:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "ukisai/Swift-Inkling-2-Mini-MLX-bf16"
Configure Hermes
# Install Hermes: curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash hermes setup # Point Hermes at the local server: hermes config set model.provider custom hermes config set model.base_url http://127.0.0.1:8080/v1 hermes config set model.default ukisai/Swift-Inkling-2-Mini-MLX-bf16
Run Hermes
hermes
- Atomic Chat
- OpenClaw
How to use ukisai/Swift-Inkling-2-Mini-MLX-bf16 with OpenClaw:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "ukisai/Swift-Inkling-2-Mini-MLX-bf16"
Configure OpenClaw
# Install OpenClaw: npm install -g openclaw@latest # Register the local server and set it as the default model: openclaw onboard --non-interactive --mode local \ --auth-choice custom-api-key \ --custom-base-url http://127.0.0.1:8080/v1 \ --custom-model-id "ukisai/Swift-Inkling-2-Mini-MLX-bf16" \ --custom-provider-id mlx-lm \ --custom-compatibility openai \ --custom-text-input \ --accept-risk \ --skip-health
Run OpenClaw
openclaw agent --local --agent main --message "Hello from Hugging Face"
Add MLX BF16 build
Browse filesFiles changed (21)
- .gitattributes+3
- LICENSEAdded+233
- NOTICEAdded+14
- README.mdAdded+127
- __pycache__/inkling2_loop.cpython-312.pycAdded+3
- chat_template.jinjaAdded+137
- config.jsonAdded+129
- generation_config.jsonAdded+6
- inkling2_loop.pyAdded+2003
- inkling2_processor.pyAdded+88
- model-00001-of-00004.safetensorsAdded+3
- model-00002-of-00004.safetensorsAdded+3
- model-00003-of-00004.safetensorsAdded+3
- model-00004-of-00004.safetensorsAdded+3
- model.safetensors.index.jsonAdded
- processor_config.jsonAdded+25
- special_tokens_map.jsonAdded+21
- tiktoken/tokenizer.modelAdded+3
- tokenizer.jsonAdded+3
- tokenizer_config.jsonAdded+84
- ukisai-banner.pngAdded
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines33343536373832 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text__pycache__/inkling2_loop.cpython-312.pyc filter=lfs diff=lfs merge=lfs -texttokenizer.json filter=lfs diff=lfs merge=lfs -textukisai-banner.png filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233Swift Open License v1.0
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, anddistribution as defined by this document.
"Licensor" shall mean UkisAI.
"Legal Entity" shall mean the union of the acting entity and all other entitiesthat control, are controlled by, or are under common control with that entity.For the purposes of this definition, "control" means (i) the power, direct orindirect, to cause the direction or management of such entity, whether bycontract or otherwise, or (ii) ownership of fifty percent (50%) or more of theoutstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercisingpermissions granted by this License.
"Source" form shall mean the preferred form for making modifications,including but not limited to software source code, documentation source,configuration files, and model weights in an unquantized, trainable format.
"Object" form shall mean any form resulting from mechanical transformation ortranslation of a Source form, including but not limited to compiled objectcode, generated documentation, quantized or otherwise converted model weights,and conversions to other media types or file formats.
"Base Model" shall mean the Qwen3.8-27B model, Copyright 2026 Alibaba Cloud,made available at https://huggingface.co/Qwen/Qwen3.8-27B, including itsweights, configuration, tokenizer, and chat template, in any form.
"Base Model License" shall mean the Apache License, Version 2.0, under whichthe Base Model is made available. A copy is distributed with the Work in thefile LICENSE-APACHE-2.0.
"Swift Contribution" shall mean the modifications to the Base Model authoredby Licensor, in any form, including without limitation adapted model weights,weight deltas, model weights to the extent they differ from the Base Model, andany configuration, documentation, and evaluation materials created by Licensorand distributed with the Work.
"Work" shall mean the Swift Contribution together with, to the extent ofLicensor's rights therein, the Derivative Work of the Base Model made availableby Licensor under this License (as indicated by a copyright notice that isincluded in or attached to the work), in any format made available by Licensor.
"Derivative Works" shall mean any work, whether in Source or Object form, thatis based on (or derived from) the Work and for which the editorial revisions,annotations, elaborations, or other modifications represent, as a whole, anoriginal work of authorship. For the purposes of this License, Derivative Worksshall not include works that remain separable from, or merely link (or bind byname) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the originalversion of the Work and any modifications or additions to that Work orDerivative Works thereof, that is intentionally submitted to Licensor forinclusion in the Work by the copyright owner or by an individual or LegalEntity authorized to submit on behalf of the copyright owner. For the purposesof this definition, "submitted" means any form of electronic, verbal, orwritten communication sent to the Licensor or its representatives, includingbut not limited to communication on electronic mailing lists, source codecontrol systems, and issue tracking systems that are managed by, or on behalfof, the Licensor for the purpose of discussing and improving the Work, butexcluding communication that is conspicuously marked or otherwise designated inwriting by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalfof whom a Contribution has been received by Licensor and subsequentlyincorporated within the Work.
"Commercial Use" shall mean any use of the Work or a Derivative Work for director indirect commercial advantage or monetary compensation.
"Qualified Non-Profit Organization" shall mean a Legal Entity that is organizedand operated exclusively for religious, charitable, scientific, testing forpublic safety, literary, or educational purposes, and which is exempt fromfederal income tax under Section 501(c)(3) of the United States InternalRevenue Code of 1986, as amended, or any equivalent non-profit or charitableorganization in a foreign jurisdiction.
"Non-Commercial or Research Purposes" shall mean purposes that do not involveany use of the Work or a Derivative Work for Commercial Use.
"Threshold" shall mean gross revenue of one million United States dollars(US$1,000,000) or more, measured over the most recently completed fiscal yearof You together with every Legal Entity that controls, is controlled by, or isunder common control with You.
2. Grant of Copyright License. Subject to the terms and conditions of thisLicense, including the Commercial Use limitation set forth in Section 5, eachContributor hereby grants to You a perpetual, worldwide, non-exclusive,no-charge, royalty-free, irrevocable copyright license to reproduce, prepareDerivative Works of, publicly display, publicly perform, sublicense, anddistribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of thisLicense, including the Commercial Use limitation set forth in Section 5, eachContributor hereby grants to You a perpetual, worldwide, non-exclusive,no-charge, royalty-free, irrevocable (except as stated in this section) patentlicense to make, have made, use, offer to sell, sell, import, and otherwisetransfer the Work, where such license applies only to those patent claimslicensable by such Contributor that are necessarily infringed by theirContribution(s) alone or by combination of their Contribution(s) with the Workto which such Contribution(s) was submitted. If You institute patent litigationagainst any entity (including a cross-claim or counterclaim in a lawsuit)alleging that the Work or a Contribution incorporated within the Workconstitutes direct or contributory patent infringement, then any patentlicenses granted to You under this License for that Work shall terminate as ofthe date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work orDerivative Works thereof in any medium, with or without modifications, and inSource or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copyof this License; and
(b) You must cause any modified files to carry prominent notices stating thatYou changed the files; and
(c) You must retain, in the Source form of any Derivative Works that Youdistribute, all copyright, patent, trademark, and attribution notices from theSource form of the Work, excluding those notices that do not pertain to anypart of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, thenany Derivative Works that You distribute must include a readable copy of theattribution notices contained within such NOTICE file, excluding those noticesthat do not pertain to any part of the Derivative Works, in at least one of thefollowing places: within a NOTICE text file distributed as part of theDerivative Works; within the Source form or documentation, if provided alongwith the Derivative Works; or, within a display generated by the DerivativeWorks, if and wherever such third-party notices normally appear. The contentsof the NOTICE file are for informational purposes only and do not modify theLicense. You may add Your own attribution notices within Derivative Works thatYou distribute, alongside or as an addendum to the NOTICE text from the Work,provided that such additional attribution notices cannot be construed asmodifying the License; and
(e) If the copy You distribute contains any portion of the Base Model(including merged, quantized, or otherwise converted weights that incorporatethe Base Model), You must also give recipients a copy of the Base Model Licenseand must comply with the Base Model License with respect to the Base Model.
You may add Your own copyright statement to Your modifications and may provideadditional or different license terms and conditions for use, reproduction, ordistribution of Your modifications, or for any such Derivative Works as awhole, provided Your use, reproduction, and distribution of the Work otherwisecomplies with the conditions stated in this License, and provided that Section5 continues to apply to the Swift Contribution contained in any suchDerivative Works.
5. Commercial Use Limitation.
(a) The rights granted under this License for Commercial Use are conditionedupon You or Your Legal Entity not exceeding the Threshold.
(b) Any Commercial Use of the Work or a Derivative Work by a Legal Entity thatexceeds the Threshold is not licensed under this License.
(c) The Threshold shall not apply to a Qualified Non-Profit Organization's useof the Work or a Derivative Work for Non-Commercial or Research Purposes.
(d) A Legal Entity that exceeds the Threshold may obtain a separate writtenlicense for Commercial Use from Licensor (the "Swift Enterprise License").Contact: https://ukisai.com/contact.
6. Base Model Rights. The Work incorporates the Base Model. Nothing in thisLicense limits, restricts, conditions, or modifies any rights You have in theBase Model under the Base Model License, and the Base Model remains availableto You from its licensor under the Base Model License. Sections 5 and 12 ofthis License apply solely to the Swift Contribution and to the Work or anyDerivative Work to the extent it contains, incorporates, or is derived from theSwift Contribution.
7. Submission of Contributions. Unless You explicitly state otherwise, anyContribution intentionally submitted for inclusion in the Work by You to theLicensor shall be under the terms and conditions of this License, without anyadditional terms or conditions. Notwithstanding the above, nothing herein shallsupersede or modify the terms of any separate license agreement you may haveexecuted with Licensor regarding such Contributions.
8. Trademarks. This License does not grant permission to use the trade names,trademarks, service marks, or product names of the Licensor (including "UkisAI"and "Swift"), except for the reasonable and customary use in describing theorigin of the Work and reproducing the content of the NOTICE file.
9. Disclaimer of Warranty. Unless required by applicable law or agreed to inwriting, Licensor provides the Work (and each Contributor provides itsContributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANYKIND, either express or implied, including, without limitation, any warrantiesor conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR APARTICULAR PURPOSE. You are solely responsible for determining theappropriateness of using or redistributing the Work and assume any risksassociated with Your exercise of permissions under this License.
10. Limitation of Liability. In no event and under no legal theory, whether intort (including negligence), contract, or otherwise, unless required byapplicable law (such as deliberate and grossly negligent acts) or agreed to inwriting, shall any Contributor be liable to You for damages, including anydirect, indirect, special, incidental, or consequential damages of anycharacter arising as a result of this License or out of the use or inability touse the Work (including but not limited to damages for loss of goodwill, workstoppage, computer failure or malfunction, or any and all other commercialdamages or losses), even if such Contributor has been advised of thepossibility of such damages.
11. Accepting Warranty or Additional Liability. While redistributing the Workor Derivative Works thereof, You may choose to offer, and charge a fee for,acceptance of support, warranty, indemnity, or other liability obligationsand/or rights consistent with this License. However, in accepting suchobligations, You may act only on Your own behalf and on Your soleresponsibility, not on behalf of any other Contributor, and only if You agreeto indemnify, defend, and hold each Contributor harmless for any liabilityincurred by, or claims asserted against, such Contributor by reason of youraccepting any such warranty or additional liability.
12. Termination. This License will terminate automatically and immediately ifYou fail to comply with any of its terms and conditions. Upon termination, Youmust cease all use of the Swift Contribution and of any Work or DerivativeWorks containing it, and delete all copies in Your possession. Termination doesnot affect Your rights in the Base Model under the Base Model License.
END OF TERMS AND CONDITIONS
APPENDIX: Notice for redistributors (quantizations, conversions, merges).
Copyright 2026 UkisAI. Swift Contribution licensed under the Swift Open License v1.0 (https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-27b/blob/main/LICENSE). Derivative of Qwen3.8-27B, Copyright 2026 Alibaba Cloud, Apache License 2.0.1234567891011121314Swift Inkling 2 MiniCopyright 2026 UkisAI
UkisAI's contribution (the "Swift Contribution") is licensed under theSwift Open License v1.0. See LICENSE.
This model is a Derivative Work of Inkling 2 Mini https://huggingface.co/thinkingmachines/Inkling-2-Mini Copyright the Inkling authors Distributed under the Inkling 2 Mini model license terms.
Changes made by UkisAI (change notice): - Model weights adapted by UkisAI using Swift post-training methods. - README.md: new. LICENSE and NOTICE added.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127---license: otherlicense_name: swift-open-license-1.0license_link: https://huggingface.co/ukisai/Swift-Inkling-2-Mini/blob/main/LICENSEbase_model: ukisai/Swift-Inkling-2-Minibase_model_relation: quantizedlibrary_name: mlx-lmpipeline_tag: image-text-to-textlanguage:- entags:- mlx- apple-silicon- inkling- looped-transformer- mixture-of-experts- efficient-thinking- reasoning- token-efficient- swift---
<div align="center"> <a href="https://ukisai.com"><img src="ukisai-banner.png" alt="UkisAI" style="width:100%;max-width:100%;height:auto;display:block;margin-bottom:0.6em;" /></a> <div style="display:flex;justify-content:center;gap:0.6em;margin-bottom:1em;"> <a href="https://ukisai.com"><strong>Website</strong></a> • <a href="https://huggingface.co/ukisai/Swift-Inkling-2-Mini"><strong>Source model</strong></a> • <a href="https://huggingface.co/ukisai/Swift-Inkling-2-Mini/blob/main/LICENSE"><strong>License</strong></a> </div></div>
# Swift Inkling 2 Mini — MLX BF16
MLX build of [Swift Inkling 2 Mini](https://huggingface.co/ukisai/Swift-Inkling-2-Mini) for Applesilicon. The routed experts keep the source checkpoint's native NVFP4/MXFP8 representation;MLX-LM decodes it through the included `inkling2_loop.py` model file.
- **Repository size:** 19.6 GB- **Precision:** No affine requantization of attention; routed experts remain native NVFP4/MXFP8, as in the source checkpoint.- **Architecture:** `Inkling2LoopForConditionalGeneration` / `inkling2_loop`- **Draft head:** the upstream DSpark MTP draft is not included.- **Recommended runtime:** `mlx-lm` 0.32.2+ on Apple Silicon with at least 32 GB unified memory.
## Installation
```bashpip install -U "mlx-lm>=0.32.2" pillow```
## Text generation
```pythonfrom mlx_lm.utils import loadfrom mlx_lm.generate import stream_generatefrom mlx_lm.sample_utils import make_sampler
model, tokenizer = load("ukisai/Swift-Inkling-2-Mini-MLX-bf16", trust_remote_code=True)
messages = [ {"role": "user", "content": "Explain why the sky is blue in two sentences."},]prompt = tokenizer.apply_chat_template( messages, add_generation_prompt=True, reasoning_effort="max", # none, minimal, low, medium, high, xhigh, max tokenize=False,)sampler = make_sampler(temp=1.0, top_p=0.95, top_k=20)
for response in stream_generate(model, tokenizer, prompt, max_tokens=1024, sampler=sampler): print(response.text, end="", flush=True)```
## Image input
The repo includes `inkling2_processor.py`. Stock `mlx-lm` can use it directly until the upstreamInkling processor PR is merged.
```pythonimport jsonimport os
import mlx.core as mxfrom inkling2_processor import Processorfrom mlx_lm.generate import stream_generatefrom mlx_lm.sample_utils import make_samplerfrom mlx_lm.utils import load, model_package
model, tokenizer = load("ukisai/Swift-Inkling-2-Mini-MLX-bf16", trust_remote_code=True)with open(os.path.join(model_package("ukisai/Swift-Inkling-2-Mini-MLX-bf16"), "config.json")) as f: config = json.load(f)processor = Processor.from_config(config)
image = processor.load_image("photo.jpg")image_prompt, pixel_values = processor( "<|message_user|><|content_image|><|unused_200054|><|end_message|>", images=[image])prompt_ids = tokenizer.encode(image_prompt, add_special_tokens=False)input_embeddings = model.embed_inputs(mx.array(prompt_ids), pixel_values=pixel_values)mx.eval(input_embeddings)
sampler = make_sampler(temp=1.0, top_p=0.95, top_k=20)for response in stream_generate( model, tokenizer, prompt_ids, max_tokens=1024, sampler=sampler, input_embeddings=input_embeddings,): print(response.text, end="", flush=True)```
`inkling2_processor.py` expands the image token into the number of tokens required by the visionencoder. The DSpark MTP draft is not used for image input.
## Precision notes
Swift Inkling 2 Mini is distributed in a mixed NVFP4/MXFP8 format. These builds preserve thatexpert format instead of dequantizing to a 52 GB BF16 checkpoint. The BF16 buildNo affine requantization of attention; routed experts remain native NVFP4/MXFP8, as in the source checkpoint..
The model file uses the upstream mlx-lm Inkling 2 implementation and is self-contained withthe `model_file` hook in `config.json`. `trust_remote_code=True` is required because`inkling2_loop` is not registered in the released MLX-LM model registry.
## License and attribution
This is a quantized derivative of Swift Inkling 2 Mini. UkisAI's contribution remains under theSwift Open License v1.0; use also complies with the base model's license terms. See[LICENSE](LICENSE) and [NOTICE](NOTICE).123version https://git-lfs.github.com/spec/v1oid sha256:a4fb2f147c9fffbd60024c13c1b3b330e8639cf210e3dc9c6b6639498f3747bfsize 109623123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137{%- set effort_map = {"none": 0.0, "minimal": 0.1, "low": 0.2, "medium": 0.7, "high": 0.9, "xhigh": 0.99, "max": 0.99} -%}{%- set role_token = {"user": "<|message_user|>", "assistant": "<|message_model|>", "system": "<|message_system|>", "tool": "<|message_tool|>"} -%}
{%- macro emit_thinking_effort() -%} {%- set eff = reasoning_effort if reasoning_effort is defined and reasoning_effort is not none else 0.9 -%} {%- if eff is string -%} {%- set key = eff | trim -%} {%- if key not in effort_map -%} {{- raise_exception("Unknown reasoning_effort: " ~ eff) -}} {%- endif -%} {%- set num = effort_map[key] -%} {%- else -%} {%- set num = eff | float -%} {%- endif -%} {%- if num < 0.0 or num > 0.99 -%} {{- raise_exception("reasoning_effort must be in [0.0, 0.99]") -}} {%- endif -%} {{- "<|message_system|><|content_text|>Thinking effort level: " -}} {%- if num == 0.0 -%}0{%- else -%}{{ num }}{%- endif -%} {{- "<|end_message|>" -}}{%- endmacro -%}
{%- if tools -%} {%- set tool_state = namespace(specs=[]) -%} {%- for tool in tools -%} {%- set fn = tool.function if tool.function is defined else tool -%} {%- set spec = { "description": (fn.description if fn.description is defined and fn.description else ""), "name": fn.name, "parameters": (fn.parameters if fn.parameters is defined and fn.parameters else {}), "type": (tool.type if tool.type is defined and tool.type else "function"), } -%} {%- set tool_state.specs = tool_state.specs + [spec] -%} {%- endfor -%} {{- "<|message_system|>tool_declare<|content_xml|>" -}} {{- tool_state.specs | tojson(sort_keys=true, separators=(",", ":")) -}} {{- "<|end_message|>" -}}{%- endif -%}
{%- set state = namespace(effort_emitted=false) -%}{%- for message in messages -%} {%- if message.role not in role_token -%} {{- raise_exception("Unknown message role: " ~ message.role) -}} {%- endif -%} {%- if not state.effort_emitted and message.role != "system" -%} {{- emit_thinking_effort() -}} {%- set state.effort_emitted = true -%} {%- endif -%}
{%- set header = namespace(text=role_token[message.role]) -%} {%- if message.role == "tool" -%} {%- if message.name is defined and message.name -%} {%- set header.text = header.text ~ message.name -%} {%- elif message.tool_call_id is defined and message.tool_call_id -%} {%- for prev in messages -%} {%- if prev.role == "assistant" and prev.tool_calls -%} {%- for tc in prev.tool_calls -%} {%- if tc.id is defined and tc.id == message.tool_call_id and tc.function.name is defined -%} {%- set header.text = header.text ~ tc.function.name -%} {%- endif -%} {%- endfor -%} {%- endif -%} {%- endfor -%} {%- endif -%} {%- elif message.role == "assistant" and message.name is defined and message.name -%} {%- set header.text = header.text ~ message.name -%} {%- endif -%} {%- set rtok = header.text -%} {%- set rendered -%}
{%- if message.role == "assistant" and message.reasoning_content is defined and message.reasoning_content -%} {{- rtok ~ "<|content_thinking|>" ~ message.reasoning_content ~ "<|end_message|>" -}} {%- endif -%}
{%- if message.content is string and (message.content or not (message.role == "assistant" and (message.tool_calls or message.reasoning_content))) -%} {{- rtok ~ "<|content_text|>" ~ message.content ~ "<|end_message|>" -}} {%- elif message.content -%} {%- for part in message.content -%} {%- if part is string -%} {{- rtok ~ "<|content_text|>" ~ part ~ "<|end_message|>" -}} {%- elif part.type is not defined or part.type in ("text", "input_text") -%} {%- set text_part = (part.text if part.text is defined and part.text is string else "") -%} {{- rtok ~ "<|content_text|>" ~ text_part ~ "<|end_message|>" -}} {%- elif part.type in ("image", "input_image", "image_url") -%} {%- if message.role not in ("user", "tool") -%} {{- raise_exception("Image content is only supported for user and tool messages") -}} {%- endif -%} {{- rtok ~ "<|content_image|><|unused_200054|><|end_message|>" -}} {%- elif part.type in ("audio", "input_audio", "audio_url") -%} {{- raise_exception("Inkling 2 does not accept audio input") -}} {%- else -%} {{- raise_exception("Unsupported content part type: " ~ part.type) -}} {%- endif -%} {%- endfor -%} {%- endif -%}
{%- if message.role == "assistant" and message.tool_calls -%} {%- for tc in message.tool_calls -%} {%- set fn = tc.function -%} {%- if fn.name is not defined or fn.name is not string -%} {{- raise_exception("tool call function name must be a string") -}} {%- endif -%} {%- if message.name is defined and message.name and message.name != fn.name -%} {{- raise_exception("assistant name " ~ message.name ~ " does not match its tool call " ~ fn.name) -}} {%- endif -%} {%- set args = fn.arguments if fn.arguments is defined and fn.arguments else {} -%} {%- if args is string -%} {{- raise_exception("tool call arguments must be a parsed object, not a JSON string; canonicalize upstream") -}} {%- endif -%} {%- if args is not mapping -%} {{- raise_exception("tool call arguments must be an object") -}} {%- endif -%} {{- "<|message_model|>" ~ fn.name ~ "<|content_invoke_tool_json|>" -}} {{- '{"name":' ~ (fn.name | tojson(sort_keys=true, separators=(",", ":"))) ~ ',"args":' -}} {{- "{" -}} {%- for key, value in args | dictsort(case_sensitive=true) -%} {{- (key | tojson) ~ ":" ~ (value | tojson(separators=(",", ":"))) -}} {%- if not loop.last -%},{%- endif -%} {%- endfor -%} {{- "}}<|end_message|>" -}} {%- endfor -%} {%- endif -%}
{%- if message.role == "assistant" -%} {{- "<|content_model_end_sampling|>" -}} {%- endif -%} {%- endset -%} {%- if message.role == "assistant" -%} {%- generation -%}{{- rendered -}}{%- endgeneration -%} {%- else -%} {{- rendered -}} {%- endif -%}{%- endfor -%}
{%- if not state.effort_emitted -%} {{- emit_thinking_effort() -}}{%- endif -%}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129{ "architectures": [ "Inkling2LoopForConditionalGeneration" ], "dtype": "bfloat16", "eos_token_id": 200006, "model_file": "inkling2_loop.py", "model_type": "inkling2_loop", "mtp_config": { "hidden_size": 2304, "num_hidden_layers": 3, "num_attention_heads": 24, "num_key_value_heads": 8, "head_dim": 128, "intermediate_size": 9216, "max_position_embeddings": 1048576, "torch_dtype": "bfloat16", "q_bias": false, "o_bias": false, "rms_norm_eps": 1e-06, "rope_theta": 1000000.0, "local_layer_ids": [ 0, 2 ], "sliding_window_size": 1024, "block_size": 8, "markov_rank": 256, "markov_head_type": "rnn_hidden", "target_layer_ids": [ 5, 23, 41, 48 ] }, "quantization": { "group_size": 16, "bits": 4, "mode": "nvfp4" }, "quantization_config": { "group_size": 16, "bits": 4, "mode": "nvfp4" }, "text_config": { "model_type": "inkling2_loop_text", "model_max_length": 1048576, "torch_dtype": "bfloat16", "hidden_size": 2304, "num_hidden_layers": 24, "vocab_size": 201024, "num_attention_heads": 24, "num_key_value_heads": 8, "head_dim": 128, "d_rel": 16, "rel_extent": 1024, "q_bias": false, "o_bias": false, "log_scaling_n_floor": 8192, "log_scaling_alpha": 0.1, "rms_norm_eps": 1e-06, "use_value_norm_no_gamma": true, "qk_l2_clip_threshold": 22.627416997969522, "rel_l2_clip_threshold": 8.0, "local_layer_ids": [ 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22 ], "sconv_kernel_size": 4, "unpadded_vocab_size": 200058, "final_logit_softcapping": 30.0, "swa_head_dim": 128, "swa_num_attention_heads": 24, "swa_num_key_value_heads": 8, "sliding_window_size": 1024, "n_layers_per_attn_res_block": 6, "attn_res_normalize_values": true, "n_routed_experts": 128, "num_experts_per_tok": 8, "n_shared_experts": 0, "intermediate_size": 1152, "mlp_gate_softcap": 4.0, "mlp_up_softcap": 25.0, "route_scale": 8.0, "use_gate_bias": true, "loop_config": { "core_start": 6, "core_end": 18, "num_passes": 3, "gate_rank": 64, "is_varloop": false } }, "vision_config": { "model_type": "inkling2_vision", "text_hidden_size": 2304, "temporal_patch_size": 2, "native_patch_size": 20, "adapter_merge_size": 2, "projection_hidden_dim": 4096, "projector_bias": false, "hidden_size": 1024, "num_hidden_layers": 23, "num_attention_heads": 16, "mlp_ratio": 4.0, "posemb_grid_size": 32, "layer_norm_eps": 1e-05 }}123456{ "do_sample": true, "temperature": 1.0, "eos_token_id": 200006, "pad_token_id": 199999}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003# Copyright © 2026 Apple Inc.# SPDX-License-Identifier: Apache-2.0"""Standalone Inkling 2 (looped) architecture for mlx-lm `model_file` loading.
Generated by scripts/build_standalone_inkling2.py -- do not edit by hand.
Inkling 2 Mini runs its middle 12 layers three times per token (48 layer visitsfrom 24 physical layers). The published checkpoint stores its routed experts asNVFP4 (layers 0-19) and MXFP8 (layers 20-23); `sanitize` reconstructsthe float carriers for those formats.
Requires `trust_remote_code=True` because mlx-lm resolves an unregistered`model_type` only through a `model_file` key."""
import mathimport refrom dataclasses import dataclassfrom functools import partialfrom typing import Any, Callable
import mlx.core as mxfrom mlx import nnfrom mlx.nn.layers.distributed import shard_linear, sum_gradientsfrom mlx.utils import tree_unflatten
from mlx_lm.kernels.expert_routing import expert_routingfrom mlx_lm.models.base import BaseModelArgsfrom mlx_lm.models.cache import ( ArraysCache, BatchRotatingKVCache, CacheList, KVCache, RotatingKVCache,)from mlx_lm.models.switch_layers import SwitchLinear, _gather_sort, _scatter_unsort
__all__ = [ "Attention", "BlockAttentionResidual", "DecoderLayer", "DynamicShortConvolution", "Experts", "FullAttention", "FullDecoderLayer", "Inkling2TextModel", "L2Clip", "MessageGate", "MessageInput", "Model", "ModelArgs", "ShortConvolution", "SlidingDecoderLayer", "TextArgs", "VisionArgs", "VisionModel", "relative_attention", "depth_attention", "sanitize", "unweighted_rms_norm",]
# ---------------------------------------------------------------------------# Inlined from mlx_lm.layers.common / mlx_lm.layers.distributed# ---------------------------------------------------------------------------def splice( embeddings: mx.array, inputs: mx.array, *, rows: mx.array, token_id: int,) -> mx.array: """The embeddings with the rows, in order, at the token_id positions of inputs.""" if rows.shape[0] == 0: return embeddings mask = inputs == token_id idx = mx.cumsum(mask.flatten()).reshape(mask.shape) - 1 idx = mx.clip(idx, 0, rows.shape[0] - 1) selected = rows[idx].astype(embeddings.dtype) return mx.where(mask[..., None], selected, embeddings)
def gather_last_axis(x: mx.array, group: mx.distributed.Group) -> mx.array: """Gather the last axis of ``x``, which is split across ``group``.""" n, size = group.size(), x.shape[-1] parts = mx.distributed.all_gather(x.reshape(-1, size), group=group) parts = parts.reshape(n, -1, size).transpose(1, 0, 2) return parts.reshape(*x.shape[:-1], n * size)
class PipelineMixin: def __init__(self): super().__init__() self.pipeline_rank = 0 self.pipeline_size = 1 self.start_idx = 0 self.end_idx = None
@property def pipeline_layers(self): return self.layers[self.start_idx : self.end_idx]
def pipeline(self, group, split=None): self.pipeline_rank = group.rank() self.pipeline_size = group.size() if split is None: base, extra = divmod(len(self.layers), self.pipeline_size) split = [base + (1 if r < extra else 0) for r in range(self.pipeline_size)] if len(split) != self.pipeline_size: raise ValueError( f"split has {len(split)} entries for group size {self.pipeline_size}" ) if any(s <= 0 for s in split) or sum(split) != len(self.layers): raise ValueError( f"split {split} must be positive and sum to {len(self.layers)} layers" ) self.start_idx = sum(split[self.pipeline_rank + 1 :]) self.end_idx = self.start_idx + split[self.pipeline_rank] self.layers = self.layers[: self.end_idx] self.layers[: self.start_idx] = [None] * self.start_idx
# ---------------------------------------------------------------------------# Inlined from mlx_lm.models.muse_spark.model# ---------------------------------------------------------------------------_MAX_COPY_ELEMENTS = 128 * 1024 * 1024
def shard_experts_inplace( module: nn.Module, sharding: str, group: mx.distributed.Group) -> None: N, r = group.size(), group.rank() updates = {} for name, w in module.parameters().items(): if not isinstance(w, mx.array): continue if w.ndim < 3: continue axis = w.ndim - 2 if sharding == "all-to-sharded" else w.ndim - 1 n = w.shape[axis] // N lo, hi = r * n, (r + 1) * n per_expert = w.size // w.shape[0] step = max(1, _MAX_COPY_ELEMENTS // (2 * per_expert)) parts = [] for i in range(0, w.shape[0], step): chunk = w[i : i + step] chunk = chunk[:, lo:hi] if axis == 1 else chunk[..., lo:hi] chunk = mx.contiguous(chunk) mx.eval(chunk) parts.append(chunk) updates[name] = mx.concatenate(parts, axis=0) if len(parts) > 1 else parts[0] module.update(updates)
# ---------------------------------------------------------------------------# Inlined from mlx_lm.kernels._common# ---------------------------------------------------------------------------from functools import lru_cache # noqa: E402
@lru_cachedef scalar(value: float, dtype: mx.Dtype = mx.float32) -> mx.array: """A cached 0-d array, which a kernel gets as a constant.""" return mx.array(value, dtype=dtype)
def row_threads(dim: int) -> int: """Threads for a threadgroup that handles one row of dim values.""" return min(1024, max(32, dim // 8 // 32 * 32))
# =========================================================================# from mlx_lm/models/inkling2/config.py# =========================================================================# Copyright © 2026 Apple Inc.
from dataclasses import dataclass
from mlx_lm.models.base import BaseModelArgs
__all__ = [ "ModelArgs", "TextArgs", "VisionArgs",]
@dataclassclass TextArgs(BaseModelArgs): hidden_size: int num_hidden_layers: int vocab_size: int unpadded_vocab_size: int num_attention_heads: int num_key_value_heads: int head_dim: int swa_num_attention_heads: int swa_num_key_value_heads: int swa_head_dim: int sliding_window_size: int local_layer_ids: list[int] d_rel: int rel_extent: int log_scaling_n_floor: int log_scaling_alpha: float rms_norm_eps: float qk_l2_clip_threshold: float rel_l2_clip_threshold: float sconv_kernel_size: int n_layers_per_attn_res_block: int n_routed_experts: int num_experts_per_tok: int intermediate_size: int mlp_gate_softcap: float mlp_up_softcap: float route_scale: float final_logit_softcapping: float loop_config: dict | None = None
def __post_init__(self): loop = self.loop_config or {} self.loop_core = range(loop.get("core_start", 0), loop.get("core_end", 0))
@dataclassclass VisionArgs(BaseModelArgs): hidden_size: int = 1024 num_hidden_layers: int = 23 num_attention_heads: int = 16 num_channels: int = 3 native_patch_size: int = 20 adapter_merge_size: int = 2 posemb_grid_size: int = 32 projection_hidden_dim: int = 4096 projector_bias: bool = False mlp_ratio: float = 4.0 layer_norm_eps: float = 1e-5 rope_theta: float = 10000.0
def __post_init__(self): self.head_dim = self.hidden_size // self.num_attention_heads self.intermediate_size = int(self.hidden_size * self.mlp_ratio)
@dataclassclass ModelArgs(BaseModelArgs): model_type: str text_config: dict vision_config: dict | None = None image_token_id: int = 200054
def __post_init__(self): self.text = TextArgs.from_dict(self.text_config) self.vision = None if self.vision_config: self.vision = VisionArgs.from_dict(self.vision_config)
# =========================================================================# from mlx_lm/models/inkling2/kernels.py# =========================================================================# Copyright © 2026 Apple Inc.
import mlx.core as mx
__all__ = [ "depth_attention", "relative_attention",]
# Attention of learned queries over the depth sources of each token, in one# kernel._DEPTH_ATTENTION_SOURCE = """ constexpr int N = K + 1; uint row = threadgroup_position_in_grid.x; uint rows = threadgroups_per_grid.x; uint tid = thread_position_in_threadgroup.x; uint lane = thread_index_in_simdgroup; uint sg = simdgroup_index_in_threadgroup;
float acc[N * Q]; for (int i = 0; i < N * Q; i++) { acc[i] = 0.0f; } for (int d = tid; d < D; d += TG) { float x[N]; for (int i = 0; i < K; i++) { x[i] = blocks[(size_t(i) * rows + row) * D + d]; } x[K] = partial[size_t(row) * D + d]; for (int j = 0; j < Q; j++) { float qv = queries[j * D + d]; for (int i = 0; i < N; i++) { acc[i * Q + j] += x[i] * qv; } } }
threadgroup float buf[N * Q][TG / 32]; for (int i = 0; i < N * Q; i++) { float v = simd_sum(acc[i]); if (lane == 0) { buf[i][sg] = v; } } threadgroup_barrier(mem_flags::mem_threadgroup);
float w[N * Q]; for (int i = 0; i < N * Q; i++) { float t = 0.0f; for (int s = 0; s < TG / 32; s++) { t += buf[i][s]; } w[i] = t * scale; } for (int j = 0; j < Q; j++) { float m = -INFINITY; for (int i = 0; i < N; i++) { m = max(m, w[i * Q + j]); } float z = 0.0f; for (int i = 0; i < N; i++) { w[i * Q + j] = metal::exp(w[i * Q + j] - m); z += w[i * Q + j]; } for (int i = 0; i < N; i++) { w[i * Q + j] /= z; } }
for (int d = tid; d < D; d += TG) { float x[N]; for (int i = 0; i < K; i++) { x[i] = blocks[(size_t(i) * rows + row) * D + d]; } x[K] = partial[size_t(row) * D + d]; for (int j = 0; j < Q; j++) { float o = 0.0f; for (int i = 0; i < N; i++) { o += w[i * Q + j] * x[i]; } out[(size_t(row) * Q + j) * D + d] = o; } }"""
_depth_attention_kernel = mx.fast.metal_kernel( name="depth_attention", input_names=["blocks", "partial", "queries", "scale"], output_names=["out"], source=_DEPTH_ATTENTION_SOURCE,)
def depth_attention( blocks: mx.array, partial: mx.array, queries: mx.array, *, scale: float) -> mx.array: """blocks: (K, ..., D) and partial: (..., D), float32, also the values. queries: float32 (Q, D). Returns (..., Q, D).""" D = partial.shape[-1] Q = queries.shape[0] TG = row_threads(D) return _depth_attention_kernel( inputs=[blocks, partial, queries, scalar(scale)], template=[("K", blocks.shape[0]), ("D", D), ("Q", Q), ("TG", TG)], grid=(partial.size // D * TG, 1, 1), threadgroup=(TG, 1, 1), output_shapes=[partial.shape[:-1] + (Q, D)], output_dtypes=[mx.float32], )[0]
# Causal flash attention with a relative position bias and a sink logit per# query.# Queries per threadgroup, 8 for each of its 4 simdgroups._BQ = 32
_TG = 128
# The online softmax of each row starts from its sink logit, so the zero-value# sink needs no key._RELATIVE_ATTENTION_SOURCE = """ constexpr float LOG2E = 1.4426950408889634f; constexpr int BK = 16; constexpr int LDK = BK + 8; constexpr int LDV = D + 8; const int L = sizes[0]; const int S = sizes[1]; const uint tid = thread_position_in_threadgroup.x; const uint sg = simdgroup_index_in_threadgroup; const uint lane = thread_index_in_simdgroup; const int batch = threadgroup_position_in_grid.z; const int head = threadgroup_position_in_grid.y; const int kv_head = head / (HQ / HKV); const int q0 = threadgroup_position_in_grid.x * BQ; const int start = key_start[batch]; const float qscale = scale * LOG2E;
// The lane holds row fm and columns fn, fn + 1 of each 8x8 fragment. const short fm = ((lane / 4) & 4) + (lane / 2) % 4; const short fn = ((lane / 4) & 2) * 2 + (lane % 2) * 2; const int row = q0 + int(sg) * 8 + fm; const bool row_ok = row < L; const int diag = S - L + row;
// q and k are clipped and v has unit RMS, so half holds them. threadgroup half Ks[D * LDK]; threadgroup half Vs[BK * LDV];
simdgroup_half8x8 q_frag[D / 8]; for (int db = 0; db < D / 8; ++db) { half2 qv = half2(0.0h); if (row_ok) { const device T* qp = q + batch * q_strides[0] + head * q_strides[1] + row * q_strides[2] + db * 8 + fn; qv = half2(float(qp[0]), float(qp[1])); } q_frag[db].thread_elements()[0] = qv.x; q_frag[db].thread_elements()[1] = qv.y; } simdgroup_float8x8 acc[D / 8]; for (int db = 0; db < D / 8; ++db) { acc[db] = make_filled_simdgroup_matrix<float, 8, 8>(0.0f); } float row_max = row_ok ? float(sinks[(batch * L + row) * HQ + head]) * LOG2E : 0.0f; float row_sum = 1.0f; const int bias_row = batch * L + (row_ok ? row : 0); const device T* bias = rel + (size_t(bias_row) * HQ + head) * R;
const int first_diag = S - L + q0; const int last_diag = S - L + min(q0 + BQ, L) - 1; int first_key = WINDOW > 0 ? max(0, first_diag - WINDOW + 1) : 0; first_key = max(first_key, start); const device T* k_head = k + batch * k_strides[0] + kv_head * k_strides[1]; const device T* v_head = v + batch * v_strides[0] + kv_head * v_strides[1];
for (int k0 = first_key / BK * BK; k0 <= last_diag; k0 += BK) { threadgroup_barrier(mem_flags::mem_threadgroup); for (int c = tid; c < BK * D / 8; c += TG) { const int r = c / (D / 8); const int col = (c % (D / 8)) * 8; const int key = k0 + r; vec<T, 4> kv[2] = {vec<T, 4>(0), vec<T, 4>(0)}; vec<T, 4> vv[2] = {vec<T, 4>(0), vec<T, 4>(0)}; if (key < S) { auto kp = (const device vec<T, 4>*)(k_head + key * k_strides[2] + col); auto vp = (const device vec<T, 4>*)(v_head + key * v_strides[2] + col); kv[0] = kp[0]; kv[1] = kp[1]; vv[0] = vp[0]; vv[1] = vp[1]; } for (int j = 0; j < 8; ++j) { Ks[(col + j) * LDK + r] = half(float(kv[j / 4][j % 4])); Vs[r * LDV + col + j] = half(float(vv[j / 4][j % 4])); } } threadgroup_barrier(mem_flags::mem_threadgroup); if (q0 + int(sg) * 8 >= L) { continue; }
simdgroup_float8x8 scores[BK / 8]; for (int kb = 0; kb < BK / 8; ++kb) { scores[kb] = make_filled_simdgroup_matrix<float, 8, 8>(0.0f); for (int db = 0; db < D / 8; ++db) { simdgroup_half8x8 k_frag; simdgroup_load(k_frag, Ks + db * 8 * LDK + kb * 8, LDK); simdgroup_multiply_accumulate(scores[kb], q_frag[db], k_frag, scores[kb]); } }
float tile_max = -INFINITY; for (int kb = 0; kb < BK / 8; ++kb) { for (int e = 0; e < 2; ++e) { const int key = k0 + kb * 8 + fn + e; const int d = diag - key; const bool visible = row_ok && d >= 0 && key >= start && (WINDOW == 0 || d < WINDOW); float s = -INFINITY; if (visible) { s = scores[kb].thread_elements()[e] * qscale; if (d < R) { s += float(bias[d]) * LOG2E; } } scores[kb].thread_elements()[e] = s; tile_max = max(tile_max, s); } } // The 4 lanes of a row are lane ^ 1 and lane ^ 8 apart. tile_max = max(tile_max, simd_shuffle_xor(tile_max, 1)); tile_max = max(tile_max, simd_shuffle_xor(tile_max, 8)); const float new_max = max(row_max, tile_max); const float factor = fast::exp2(row_max - new_max); float tile_sum = 0.0f; simdgroup_half8x8 probs[BK / 8]; for (int kb = 0; kb < BK / 8; ++kb) { for (int e = 0; e < 2; ++e) { const float p = fast::exp2(scores[kb].thread_elements()[e] - new_max); probs[kb].thread_elements()[e] = half(p); tile_sum += p; } } tile_sum += simd_shuffle_xor(tile_sum, 1); tile_sum += simd_shuffle_xor(tile_sum, 8); row_sum = row_sum * factor + tile_sum; row_max = new_max; for (int db = 0; db < D / 8; ++db) { acc[db].thread_elements()[0] *= factor; acc[db].thread_elements()[1] *= factor; for (int kb = 0; kb < BK / 8; ++kb) { simdgroup_half8x8 v_frag; simdgroup_load(v_frag, Vs + kb * 8 * LDV + db * 8, LDV); simdgroup_multiply_accumulate(acc[db], probs[kb], v_frag, acc[db]); } } }
if (row_ok) { device T* op = out + (size_t(batch * L + row) * HQ + head) * D; for (int db = 0; db < D / 8; ++db) { op[db * 8 + fn] = T(acc[db].thread_elements()[0] / row_sum); op[db * 8 + fn + 1] = T(acc[db].thread_elements()[1] / row_sum); } }"""
_relative_attention_kernel = mx.fast.metal_kernel( name="relative_attention", input_names=["q", "k", "v", "rel", "sinks", "key_start", "sizes", "scale"], output_names=["out"], source=_RELATIVE_ATTENTION_SOURCE, ensure_row_contiguous=False,)
def relative_attention( q: mx.array, k: mx.array, v: mx.array, rel: mx.array, sinks: mx.array, *, scale: float, window: int, key_start: mx.array,) -> mx.array: """q: (B, Hq, L, D), k and v: (B, Hkv, S, D), all bfloat16, with the queries at the last L keys. rel: (B, L, Hq, R), the bias at distances below R. sinks: (B, L, Hq). key_start: (B,), the first key of each row. Returns (B, L, Hq, D).""" B, Hq, L, D = q.shape Hkv, S = k.shape[1], k.shape[2] return _relative_attention_kernel( inputs=[ q, k, v, mx.contiguous(rel), mx.contiguous(sinks.astype(mx.float32)), mx.contiguous(key_start.astype(mx.int32)), mx.array([L, S], dtype=mx.int32), scalar(scale), ], template=[ ("T", q.dtype), ("D", D), ("HQ", Hq), ("HKV", Hkv), ("R", rel.shape[-1]), ("WINDOW", window), ("BQ", _BQ), ("TG", _TG), ], grid=((L + _BQ - 1) // _BQ * _TG, Hq, B), threadgroup=(_TG, 1, 1), output_shapes=[(B, L, Hq, D)], output_dtypes=[q.dtype], )[0]
# =========================================================================# from mlx_lm/models/inkling2/layers.py# =========================================================================# Copyright © 2026 Apple Inc.
import mathfrom functools import partialfrom typing import Any
import mlx.core as mxfrom mlx import nnfrom mlx.nn.layers.distributed import sum_gradients
from mlx_lm.kernels.expert_routing import expert_routingfrom mlx_lm.models.switch_layers import SwitchLinear, _gather_sort, _scatter_unsortfrom mlx_lm.models.cache import BatchRotatingKVCache, RotatingKVCache
__all__ = [ "Attention", "BlockAttentionResidual", "DecoderLayer", "DynamicShortConvolution", "Experts", "FullAttention", "FullDecoderLayer", "L2Clip", "MessageGate", "MessageInput", "RelativeLogits", "ScaledL2Clip", "ShortConvolution", "SlidingAttention", "SlidingDecoderLayer", "SoftcappedSwiGLU", "SparseMoeBlock", "TopKRouter", "unweighted_rms_norm",]
_ROUTER_SCORE_EPS = 1e-20
def _use_kernels() -> bool: return mx.default_device() == mx.gpu and mx.metal.is_available()
def unweighted_rms_norm(x: mx.array, eps: float = 1e-6) -> mx.array: return mx.fast.rms_norm(x, None, eps)
@partial(mx.compile, shapeless=True)def _l2_clip(hidden_states: mx.array, scale: mx.array, threshold: float) -> mx.array: states = hidden_states.astype(mx.float32) * scale norm = mx.sqrt((states * states).sum(axis=-1, keepdims=True)) scaled = states * mx.minimum(threshold / (norm + 1e-6), 1.0) return scaled.astype(hidden_states.dtype)
@partial(mx.compile, shapeless=True)def _softcapped_swiglu( gate: mx.array, up: mx.array, gate_softcap: float, up_softcap: float) -> mx.array: input_dtype = gate.dtype gate, up = gate.astype(mx.float32), up.astype(mx.float32) gate_capped = mx.tanh(gate / gate_softcap) * gate_softcap up_capped = mx.tanh(up / up_softcap) * up_softcap return (gate_capped * mx.sigmoid(gate) * up_capped).astype(input_dtype)
class L2Clip(nn.Module): def __init__(self, threshold: float): super().__init__() self.threshold = threshold
def __call__(self, hidden_states: mx.array) -> mx.array: return _l2_clip(hidden_states, 1.0, self.threshold)
class ScaledL2Clip(nn.Module): def __init__(self, num_heads: int, head_dim: int, threshold: float): super().__init__() self.threshold = threshold self.scale = mx.ones((num_heads, head_dim))
def __call__(self, hidden_states: mx.array) -> mx.array: return _l2_clip(hidden_states, self.scale, self.threshold)
class RelativeLogits(nn.Module): def __init__(self, d_rel: int, rel_extent: int): super().__init__() self.proj = mx.zeros((d_rel, rel_extent))
def __call__(self, relative_states: mx.array) -> mx.array: return relative_states @ self.proj.astype(relative_states.dtype)
def _conv_input( hidden_states: mx.array, conv_state: mx.array | None, conv_mask: mx.array | None, kernel_size: int,) -> mx.array: hidden_states = hidden_states.astype(mx.float32) if conv_mask is not None: hidden_states = mx.where(conv_mask[..., None], hidden_states, 0) if conv_state is None: shape = (hidden_states.shape[0], kernel_size - 1, hidden_states.shape[-1]) conv_state = mx.zeros(shape, mx.float32) return mx.concatenate([conv_state, hidden_states], axis=1)
def _conv_state(window: mx.array, lengths: mx.array | None, n: int) -> mx.array: if lengths is None: pos = mx.arange(window.shape[1] - n, window.shape[1])[None, :, None] else: ends = mx.clip(lengths, 0, window.shape[1] - n) pos = (ends[:, None] + mx.arange(n))[..., None] # A gather copies, so the state does not keep the input in memory. return mx.take_along_axis(window, pos, axis=1)
class ShortConvolution(nn.Module): def __init__(self, dims: int, kernel_size: int): super().__init__() self.kernel_size = kernel_size self.conv1d = nn.Conv1d(dims, dims, kernel_size, groups=dims, bias=False)
def __call__( self, hidden_states: mx.array, conv_state: mx.array | None, conv_mask: mx.array | None, ) -> tuple[mx.array, mx.array]: K = self.kernel_size residual = hidden_states.astype(mx.float32) window = _conv_input(hidden_states, conv_state, conv_mask, K) # As the reference, the conv runs in the weight dtype. out = self.conv1d(window.astype(self.conv1d.weight.dtype)) out = (out.astype(mx.float32) + residual) / math.sqrt(K + 1) return out.astype(hidden_states.dtype), window
class DynamicShortConvolution(nn.Module): def __init__(self, dims: int, input_dims: int, num_heads: int, kernel_size: int): super().__init__() self.kernel_size = kernel_size self.num_heads = num_heads self.static_weight = mx.zeros((kernel_size, dims)) self.weight_proj = nn.Linear(input_dims, num_heads * kernel_size, bias=False)
def __call__( self, hidden_states: mx.array, dynamic_input: mx.array, conv_state: mx.array | None, conv_mask: mx.array | None, ) -> tuple[mx.array, mx.array]: B, L, C = hidden_states.shape K, H = self.kernel_size, self.num_heads dynamic_weights = self.weight_proj(dynamic_input).astype(mx.float32) dynamic_weights = dynamic_weights.reshape(B, L, H, 1, K) static_weights = self.static_weight.astype(mx.float32).T.reshape(H, -1, K) weights = static_weights + dynamic_weights
window = _conv_input(hidden_states, conv_state, conv_mask, K) windows = mx.stack( [window[:, K - 1 - lag : K - 1 - lag + L] for lag in range(K)], axis=-1 ) windows = windows.reshape(B, L, H, -1, K) out = (windows * weights).sum(axis=-1).reshape(B, L, C) out = (out + hidden_states.astype(mx.float32)) / math.sqrt(2 * K + 1) return out.astype(hidden_states.dtype), window
def _positions(offset, length: int) -> mx.array: pos = mx.arange(length) if isinstance(offset, mx.array): return offset[:, None] + pos return pos + offset
def _key_positions(cache: Any, num_keys: int, num_queries: int, end) -> mx.array: k = mx.arange(num_keys) if num_queries == 1 and isinstance(cache, (RotatingKVCache, BatchRotatingKVCache)): # A decode step writes in place, so the keys can be rotated. k = (k - cache._idx) % num_keys if isinstance(end, mx.array): return (end - num_keys)[:, None] + k return k + (end - num_keys)
def _attention_reference( query: mx.array, key: mx.array, value: mx.array, position_bias: mx.array, sinks: mx.array, *, scale: float, window: int, query_positions: mx.array, key_positions: mx.array,) -> mx.array: B, Hq, L, D = query.shape Hkv, S = key.shape[1], key.shape[2] R = position_bias.shape[-1] distance = query_positions[..., :, None] - key_positions[..., None, :] visible = (distance >= 0) & (key_positions[..., None, :] >= 0) if window: visible = visible & (distance < window) if distance.ndim == 3: distance, visible = distance[:, None], visible[:, None] bias = mx.take_along_axis( position_bias.transpose(0, 2, 1, 3), mx.broadcast_to(mx.clip(distance, 0, R - 1), (B, Hq, L, S)), axis=-1, ) bias = mx.where(distance < R, bias.astype(mx.float32), 0.0) attention_mask = mx.where(visible, bias, -mx.inf).reshape(B, Hkv, -1, L, S)
query = query.astype(mx.float32).reshape(B, Hkv, -1, L, D) key = key.astype(mx.float32)[:, :, None] attn_weights = (query @ key.swapaxes(-1, -2)) * scale + attention_mask sinks = sinks.astype(mx.float32).transpose(0, 2, 1).reshape(B, Hkv, -1, L, 1) combined_logits = mx.concatenate([attn_weights, sinks], axis=-1) attn_weights = mx.softmax(combined_logits, axis=-1)[..., :S] attn_output = attn_weights.astype(value.dtype) @ value[:, :, None] return attn_output.reshape(B, Hq, L, D).transpose(0, 2, 1, 3)
class Attention(nn.Module): def __init__(self, args: TextArgs, *, sliding: bool): super().__init__() if sliding: self.num_heads = args.swa_num_attention_heads self.num_key_value_heads = args.swa_num_key_value_heads self.head_dim = args.swa_head_dim self.sliding_window = args.sliding_window_size rel_extent = args.sliding_window_size else: self.num_heads = args.num_attention_heads self.num_key_value_heads = args.num_key_value_heads self.head_dim = args.head_dim self.sliding_window = 0 rel_extent = args.rel_extent self.scaling = self.head_dim**-0.5
dim = args.hidden_size q_dim = self.num_heads * self.head_dim kv_dim = self.num_key_value_heads * self.head_dim self.q_proj = nn.Linear(dim, q_dim, bias=False) self.k_proj = nn.Linear(dim, kv_dim, bias=False) self.v_proj = nn.Linear(dim, kv_dim, bias=False) self.r_proj = nn.Linear(dim, self.num_heads * args.d_rel, bias=False) self.o_proj = nn.Linear(q_dim, dim, bias=False) self.gate_proj = nn.Linear(dim, q_dim, bias=False) self.sink_proj = nn.Linear(dim, self.num_heads, bias=False) self.rel_logits_proj = RelativeLogits(args.d_rel, rel_extent) self.q_l2_clip = ScaledL2Clip( self.num_heads, self.head_dim, args.qk_l2_clip_threshold ) self.k_l2_clip = L2Clip(args.qk_l2_clip_threshold) self.rel_l2_clip = ScaledL2Clip( self.num_heads, args.d_rel, args.rel_l2_clip_threshold ) self.eps = args.rms_norm_eps
def _attend( self, hidden_states: mx.array, query_states: mx.array, key_states: mx.array, value_states: mx.array, relative_states: mx.array, cache: Any | None, tau: mx.array | None = None, ) -> mx.array: B, L, _ = hidden_states.shape gate = self.gate_proj(hidden_states) sinks = self.sink_proj(hidden_states)
query_states = query_states.reshape(B, L, self.num_heads, -1) key_states = key_states.reshape(B, L, self.num_key_value_heads, -1) value_states = value_states.reshape(B, L, self.num_key_value_heads, -1) relative_states = relative_states.reshape(B, L, self.num_heads, -1) query_states = self.q_l2_clip(query_states) key_states = self.k_l2_clip(key_states) value_states = unweighted_rms_norm( value_states.astype(mx.float32), self.eps ).astype(value_states.dtype) relative_states = self.rel_l2_clip(relative_states) if tau is not None: query_states = (query_states.astype(mx.float32) * tau).astype( query_states.dtype ) relative_states = (relative_states.astype(mx.float32) * tau).astype( relative_states.dtype ) position_bias = self.rel_logits_proj(relative_states)
query_states = query_states.transpose(0, 2, 1, 3) key_states = key_states.transpose(0, 2, 1, 3) value_states = value_states.transpose(0, 2, 1, 3) if cache is not None: key_states, value_states = cache.update_and_fetch(key_states, value_states) attn_output = self._attention( query_states, key_states, value_states, position_bias, sinks, cache )
attn_output = attn_output.reshape(B, L, -1).astype(mx.float32) attn_output = attn_output * mx.sigmoid(gate.astype(mx.float32)) return self.o_proj(attn_output.astype(gate.dtype))
def _attention(self, query, key, value, position_bias, sinks, cache) -> mx.array: B, _, L, _ = query.shape S = key.shape[2] end = cache.offset if cache is not None else L bf16 = query.dtype == key.dtype == value.dtype == mx.bfloat16 if L > 1 and _use_kernels() and bf16: key_start = mx.broadcast_to(S - end, (B,)) return relative_attention( query, key, value, position_bias, sinks, scale=self.scaling, window=self.sliding_window, key_start=key_start, )
query_positions = _positions(end - L, L) key_positions = _key_positions(cache, S, L, end) if L == 1 and B == 1: # The fused attention takes the sinks of one row. distance = query_positions.reshape(1) - key_positions.reshape(S) R = position_bias.shape[-1] bias = mx.take(position_bias[0, 0], mx.clip(distance, 0, R - 1), axis=-1) bias = mx.where(distance < R, bias, mx.zeros_like(bias)) visible = (distance >= 0) & (key_positions.reshape(S) >= 0) if self.sliding_window: visible = visible & (distance < self.sliding_window) mask = mx.where(visible, bias, -mx.inf).astype(query.dtype) attn_output = mx.fast.scaled_dot_product_attention( query, key, value, scale=self.scaling, mask=mask[None, :, None, :], sinks=sinks[0, 0].astype(query.dtype), ) return attn_output.transpose(0, 2, 1, 3)
return _attention_reference( query, key, value, position_bias, sinks, scale=self.scaling, window=self.sliding_window, query_positions=query_positions, key_positions=key_positions, )
class SlidingAttention(Attention): def __init__(self, args: TextArgs): super().__init__(args, sliding=True) dims = self.num_key_value_heads * self.head_dim self.k_sconv = ShortConvolution(dims, args.sconv_kernel_size) self.v_sconv = ShortConvolution(dims, args.sconv_kernel_size)
def __call__( self, hidden_states: mx.array, key_hidden_states: mx.array, value_hidden_states: mx.array, *, cache: Any | None, conv_states: list, conv_mask: mx.array | None, ) -> mx.array: kv_cache = cache[0] if cache is not None else None key_states, conv_states[0] = self.k_sconv( self.k_proj(key_hidden_states), conv_states[0], conv_mask ) value_states, conv_states[1] = self.v_sconv( self.v_proj(value_hidden_states), conv_states[1], conv_mask ) return self._attend( hidden_states, self.q_proj(hidden_states), key_states, value_states, self.r_proj(hidden_states), kv_cache, )
class FullAttention(Attention): def __init__(self, args: TextArgs): super().__init__(args, sliding=False) dims = self.num_key_value_heads * self.head_dim conv_args = (args.hidden_size, self.num_key_value_heads, args.sconv_kernel_size) self.k_sconv = DynamicShortConvolution(dims, *conv_args) self.v_sconv = DynamicShortConvolution(dims, *conv_args) self.log_scaling_n_floor = args.log_scaling_n_floor self.log_scaling_alpha = args.log_scaling_alpha
def __call__( self, hidden_states: mx.array, key_hidden_states: mx.array, value_hidden_states: mx.array, *, cache: Any | None, conv_states: list, conv_mask: mx.array | None, ) -> mx.array: kv_cache = cache[0] if cache is not None else None key_states, conv_states[0] = self.k_sconv( self.k_proj(key_hidden_states), key_hidden_states, conv_states[0], conv_mask, ) value_states, conv_states[1] = self.v_sconv( self.v_proj(value_hidden_states), value_hidden_states, conv_states[1], conv_mask, )
offset = kv_cache.offset if kv_cache is not None else 0 position_ids = _positions(offset, hidden_states.shape[1]).astype(mx.float32) tau = 1.0 + self.log_scaling_alpha * mx.log( mx.maximum((position_ids + 1) / self.log_scaling_n_floor, 1.0) ) return self._attend( hidden_states, self.q_proj(hidden_states), key_states, value_states, self.r_proj(hidden_states), kv_cache, tau=tau[..., None, None], )
class SoftcappedSwiGLU(nn.Module): def __init__(self, args: TextArgs): super().__init__() self.gate_softcap = args.mlp_gate_softcap self.up_softcap = args.mlp_up_softcap
def __call__(self, gate: mx.array, up: mx.array) -> mx.array: return _softcapped_swiglu(gate, up, self.gate_softcap, self.up_softcap)
class Experts(nn.Module): def __init__(self, args: TextArgs): super().__init__() dims, hidden = args.hidden_size, args.intermediate_size num_experts = args.n_routed_experts # The rows alternate between gate and up, as in the checkpoint. self.gate_up_proj = SwitchLinear(dims, 2 * hidden, num_experts, bias=False) self.down_proj = SwitchLinear(hidden, dims, num_experts, bias=False) self.act_fn = SoftcappedSwiGLU(args)
def __call__(self, x: mx.array, indices: mx.array) -> mx.array: x = mx.expand_dims(x, (-2, -3)) indices = mx.stop_gradient(indices) do_sort = indices.size >= 64 idx, inv_order = indices, None if do_sort: x, idx, inv_order = _gather_sort(x, indices) gate_up = self.gate_up_proj(x, idx, sorted_indices=do_sort) x = self.act_fn(gate_up[..., 0::2], gate_up[..., 1::2]) x = self.down_proj(x, idx, sorted_indices=do_sort) if do_sort: x = _scatter_unsort(x, inv_order, indices.shape) return x.squeeze(-2)
class TopKRouter(nn.Module): def __init__(self, args: TextArgs): super().__init__() self.top_k = args.num_experts_per_tok self.routed_scaling_factor = args.route_scale num_experts, dims = args.n_routed_experts, args.hidden_size self.weight = mx.zeros((num_experts, dims), dtype=mx.float32) self.e_score_correction_bias = mx.zeros((num_experts,), dtype=mx.float32)
def __call__(self, hidden_states: mx.array) -> tuple[mx.array, mx.array]: logits = hidden_states.astype(mx.float32) @ self.weight.T if _use_kernels(): return expert_routing( logits, self.e_score_correction_bias, top_k=self.top_k, multiplier=1.0, score_eps=_ROUTER_SCORE_EPS, route_scale=self.routed_scaling_factor, ) scores = mx.sigmoid(logits) biased = scores + self.e_score_correction_bias k = self.top_k indices = mx.argpartition(-biased, kth=k - 1, axis=-1)[..., :k] weights = mx.take_along_axis(scores, indices, axis=-1) weights = weights / (weights.sum(axis=-1, keepdims=True) + _ROUTER_SCORE_EPS) return indices, weights * self.routed_scaling_factor
class SparseMoeBlock(nn.Module): def __init__(self, args: TextArgs): super().__init__() self.gate = TopKRouter(args) self.experts = Experts(args) self.sharding_group = None
def __call__(self, hidden_states: mx.array) -> mx.array: group = self.sharding_group if group is not None: hidden_states = sum_gradients(group)(hidden_states) selected_experts, routing_weights = self.gate(hidden_states) expert_states = self.experts(hidden_states, selected_experts) expert_states = expert_states.astype(mx.float32) * routing_weights[..., None] final_hidden_states = expert_states.sum(axis=-2) if group is not None: final_hidden_states = mx.distributed.all_sum( final_hidden_states, group=group ) return final_hidden_states.astype(hidden_states.dtype)
class BlockAttentionResidual(nn.Module): def __init__(self, dims: int, num_queries: int = 1): super().__init__() shape = (dims,) if num_queries == 1 else (num_queries, dims) self.query = mx.zeros(shape, dtype=mx.float32)
def __call__( self, block_states: mx.array, partial_block_states: mx.array ) -> mx.array: dims = partial_block_states.shape[-1] return _depth_attention( block_states, partial_block_states, self.query.reshape(-1, dims) )
def _depth_attention( block_states: mx.array, partial_block_states: mx.array, query: mx.array) -> mx.array: query = query.astype(mx.float32) scale = partial_block_states.shape[-1] ** -0.5 if _use_kernels(): return depth_attention(block_states, partial_block_states, query, scale=scale) stacked_states = mx.concatenate([block_states, partial_block_states[None]]) stacked_states = mx.moveaxis(stacked_states, 0, -2) weights = mx.softmax((stacked_states @ query.T) * scale, axis=-2, precise=True) return weights.swapaxes(-1, -2) @ stacked_states
class MessageGate(nn.Module): def __init__(self, dims: int, rank: int): super().__init__() self.down_proj = nn.Linear(2 * dims, rank, bias=False) self.forget_gate_proj = nn.Linear(rank, dims, bias=False) self.message_gate_proj = nn.Linear(rank, dims, bias=False)
def __call__(self, hidden_states: mx.array, message: mx.array) -> mx.array: states = mx.concatenate( [unweighted_rms_norm(hidden_states), unweighted_rms_norm(message)], axis=-1, ) states = self.down_proj(states.astype(self.down_proj.weight.dtype)) states = states.astype(mx.float32) forget_gate = mx.tanh(self.forget_gate_proj(states)) message_gate = mx.tanh(self.message_gate_proj(states)) return (1 - forget_gate) * hidden_states + message_gate * message
class MessageInput(nn.Module): def __init__(self, dims: int, num_looped_layers: int): super().__init__() # The query, key, value and mlp queries of each looped layer. self.query = mx.zeros((num_looped_layers, 4, dims), mx.float32)
def __call__(self, bank: tuple, loop_layer_idx: int) -> mx.array: return _depth_attention(*bank, self.query[loop_layer_idx])
class DecoderLayer(nn.Module): def __init__(self, args: TextArgs, layer_idx: int, *, num_queries: int): super().__init__() dims = args.hidden_size self.is_block_boundary = layer_idx % args.n_layers_per_attn_res_block == 0 self.attention_input = ( BlockAttentionResidual(dims, num_queries) if layer_idx > 0 else None ) self.mlp_input = BlockAttentionResidual(dims) self.mlp = SparseMoeBlock(args) self.post_attention_layernorm = nn.RMSNorm(dims, eps=args.rms_norm_eps) kernel_size = args.sconv_kernel_size self.post_attention_convolution = ShortConvolution(dims, kernel_size) self.post_mlp_convolution = ShortConvolution(dims, kernel_size) if layer_idx in args.loop_core: rank = args.loop_config["gate_rank"] self.q_message_gate = MessageGate(dims, rank) self.k_message_gate = MessageGate(dims, rank) self.v_message_gate = MessageGate(dims, rank) self.mlp_message_gate = MessageGate(dims, rank)
def _mix_messages(self, states: tuple, messages: mx.array) -> tuple: q_states, k_states, v_states = states return ( self.q_message_gate(q_states, messages[..., 0, :]), self.k_message_gate(k_states, messages[..., 1, :]), self.v_message_gate(v_states, messages[..., 2, :]), )
def __call__( self, hidden_states: mx.array, block_states: mx.array | None, *, cache: Any | None = None, conv_mask: mx.array | None = None, messages: mx.array | None = None, ) -> tuple[mx.array, mx.array]: dtype = hidden_states.dtype conv = cache[1] if cache is not None else None conv_states = list(conv.cache) if conv is not None else [None] * 4 block_residual = hidden_states normed_residual = unweighted_rms_norm(block_residual.astype(mx.float32))
attention_inputs = None if self.attention_input is not None: attention_inputs = self.attention_input(block_states, normed_residual) hidden_states = self._self_attention( hidden_states, attention_inputs, cache, conv_states, conv_mask, messages ) hidden_states, conv_states[2] = self.post_attention_convolution( hidden_states, conv_states[2], conv_mask )
residual = hidden_states = hidden_states.astype(mx.float32) if self.is_block_boundary: block = normed_residual[None] if block_states is None: block_states = block else: block_states = mx.concatenate([block_states, block]) else: residual = hidden_states = block_residual.astype(mx.float32) + hidden_states
normed_states = unweighted_rms_norm(hidden_states) hidden_states = self.mlp_input(block_states, normed_states)[..., 0, :] if messages is not None: hidden_states = self.mlp_message_gate(hidden_states, messages[..., 3, :]) hidden_states = self.mlp( self.post_attention_layernorm(hidden_states).astype(dtype) ) hidden_states, conv_states[3] = self.post_mlp_convolution( hidden_states, conv_states[3], conv_mask )
if conv is not None: n = self.post_mlp_convolution.kernel_size - 1 for i, window in enumerate(conv_states): conv[i] = _conv_state(window, conv.lengths, n) conv.advance(block_residual.shape[1]) hidden_states = residual + hidden_states.astype(mx.float32) return hidden_states.astype(dtype), block_states
class SlidingDecoderLayer(DecoderLayer): def __init__(self, args: TextArgs, layer_idx: int): super().__init__(args, layer_idx, num_queries=1) self.self_attn = SlidingAttention(args) self.input_layernorm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps)
def _self_attention( self, hidden_states, attention_inputs, cache, conv_states, conv_mask, messages ): dtype = hidden_states.dtype if attention_inputs is not None: hidden_states = attention_inputs[..., 0, :] if messages is None: states = (self.input_layernorm(hidden_states).astype(dtype),) * 3 else: states = self._mix_messages((hidden_states,) * 3, messages) states = [self.input_layernorm(s).astype(dtype) for s in states] return self.self_attn( *states, cache=cache, conv_states=conv_states, conv_mask=conv_mask, )
class FullDecoderLayer(DecoderLayer): def __init__(self, args: TextArgs, layer_idx: int): super().__init__(args, layer_idx, num_queries=3) self.self_attn = FullAttention(args) eps = args.rms_norm_eps self.q_input_layernorm = nn.RMSNorm(args.hidden_size, eps=eps) self.k_input_layernorm = nn.RMSNorm(args.hidden_size, eps=eps) self.v_input_layernorm = nn.RMSNorm(args.hidden_size, eps=eps)
def _self_attention( self, hidden_states, attention_inputs, cache, conv_states, conv_mask, messages ): dtype = hidden_states.dtype if attention_inputs is None: query_states = key_states = value_states = hidden_states else: query_states, key_states, value_states = ( attention_inputs[..., i, :] for i in range(3) ) if messages is not None: query_states, key_states, value_states = self._mix_messages( (query_states, key_states, value_states), messages ) return self.self_attn( self.q_input_layernorm(query_states).astype(dtype), self.k_input_layernorm(key_states).astype(dtype), self.v_input_layernorm(value_states).astype(dtype), cache=cache, conv_states=conv_states, conv_mask=conv_mask, )
# =========================================================================# from mlx_lm/models/inkling2/vision.py# =========================================================================# Copyright © 2026 Apple Inc.
import mlx.core as mxfrom mlx import nn
__all__ = [ "VisionAttention", "VisionEmbeddings", "VisionEncoderLayer", "VisionMLP", "VisionMerger", "VisionModel", "VisionRotaryEmbedding",]
def _precise_gelu(x: mx.array) -> mx.array: return nn.gelu(x.astype(mx.float32)).astype(x.dtype)
def _grid_positions(grid_h: int, grid_w: int, merge: int) -> tuple[mx.array, mx.array]: i = mx.arange(grid_h * grid_w) blocks_w = grid_w // merge row = i // (merge * merge * blocks_w) * merge + i // merge % merge col = i // (merge * merge) % blocks_w * merge + i % merge return row, col
def _bilinear_taps(index: mx.array, size: int, side: int) -> tuple[mx.array, mx.array]: src = (index.astype(mx.float32) + 0.5) * side / size - 0.5 taps = mx.floor(src)[:, None] + mx.arange(2) weights = mx.maximum(1.0 - mx.abs(src[:, None] - taps), 0.0) return mx.clip(taps, 0, side - 1).astype(mx.int32), weights
class VisionEmbeddings(nn.Module): def __init__(self, args: VisionArgs): super().__init__() self.merge_size = args.adapter_merge_size self.grid_size = args.posemb_grid_size patch_dims = args.num_channels * args.native_patch_size**2 self.patch_embedding = nn.Linear(patch_dims, args.hidden_size, bias=False) self.position_embedding = nn.Embedding( args.posemb_grid_size**2, args.hidden_size ) self.class_embedding = mx.zeros((args.hidden_size,)) self.cls_position_embedding = mx.zeros((args.hidden_size,))
def __call__(self, pixel_values: mx.array, grid_h: int, grid_w: int) -> mx.array: patch_embeddings = self.patch_embedding(pixel_values)
side = self.grid_size row, col = _grid_positions(grid_h, grid_w, self.merge_size) row_taps, row_weights = _bilinear_taps(row, grid_h, side) col_taps, col_weights = _bilinear_taps(col, grid_w, side) interp_indices = row_taps[:, :, None] * side + col_taps[:, None, :] interp_weights = row_weights[:, :, None] * col_weights[:, None, :] position_embeddings = self.position_embedding(interp_indices.reshape(-1, 4)) position_embeddings = position_embeddings.astype(mx.float32) position_embeddings = position_embeddings * interp_weights.reshape(-1, 4, 1) patch_embeddings = patch_embeddings + position_embeddings.sum(axis=1).astype( patch_embeddings.dtype )
cls_embedding = self.class_embedding + self.cls_position_embedding cls_embedding = cls_embedding.astype(patch_embeddings.dtype) return mx.concatenate([cls_embedding[None], patch_embeddings])
class VisionRotaryEmbedding(nn.Module): def __init__(self, args: VisionArgs): super().__init__() dims = args.head_dim // 2 self._inv_freq = 1.0 / ( args.rope_theta ** (mx.arange(0, dims, 2, dtype=mx.float32) / dims) )
def __call__(self, row: mx.array, col: mx.array) -> tuple[mx.array, mx.array]: freqs_h = row[:, None].astype(mx.float32) * self._inv_freq freqs_w = col[:, None].astype(mx.float32) * self._inv_freq freqs = mx.repeat(mx.concatenate([freqs_w, freqs_h], axis=-1), 2, axis=-1) return mx.cos(freqs), mx.sin(freqs)
def _apply_rotary_pos_emb_vision( hidden_states: mx.array, cos: mx.array, sin: mx.array) -> mx.array: states = hidden_states.astype(mx.float32) pairs = states.reshape(*states.shape[:-1], -1, 2) rotated = mx.stack([-pairs[..., 1], pairs[..., 0]], axis=-1).reshape(states.shape) return (states * cos + rotated * sin).astype(hidden_states.dtype)
class VisionAttention(nn.Module): def __init__(self, args: VisionArgs): super().__init__() dims = args.hidden_size self.num_heads = args.num_attention_heads self.scaling = args.head_dim**-0.5 self.q_proj = nn.Linear(dims, dims) self.k_proj = nn.Linear(dims, dims) self.v_proj = nn.Linear(dims, dims) self.out_proj = nn.Linear(dims, dims)
def __call__( self, hidden_states: mx.array, cos: mx.array, sin: mx.array ) -> mx.array: N = hidden_states.shape[0] shape = (N, self.num_heads, -1) cos, sin = cos[:, None], sin[:, None] query_states = self.q_proj(hidden_states).reshape(shape) key_states = self.k_proj(hidden_states).reshape(shape) value_states = self.v_proj(hidden_states).reshape(shape) query_states = _apply_rotary_pos_emb_vision(query_states, cos, sin) key_states = _apply_rotary_pos_emb_vision(key_states, cos, sin) query_states, key_states, value_states = ( states.transpose(1, 0, 2)[None] for states in (query_states, key_states, value_states) ) attn_output = mx.fast.scaled_dot_product_attention( query_states, key_states, value_states, scale=self.scaling ) attn_output = attn_output[0].transpose(1, 0, 2).reshape(N, -1) return self.out_proj(attn_output)
class VisionMLP(nn.Module): def __init__(self, args: VisionArgs): super().__init__() self.fc1 = nn.Linear(args.hidden_size, args.intermediate_size) self.fc2 = nn.Linear(args.intermediate_size, args.hidden_size)
def __call__(self, hidden_states: mx.array) -> mx.array: return self.fc2(_precise_gelu(self.fc1(hidden_states)))
class VisionEncoderLayer(nn.Module): def __init__(self, args: VisionArgs): super().__init__() dims, eps = args.hidden_size, args.layer_norm_eps self.self_attn = VisionAttention(args) self.mlp = VisionMLP(args) self.layernorm_before = nn.LayerNorm(dims, eps=eps) self.layernorm_after = nn.LayerNorm(dims, eps=eps) self.lambda_1 = mx.ones((dims,)) self.lambda_2 = mx.ones((dims,))
def __call__( self, hidden_states: mx.array, cos: mx.array, sin: mx.array ) -> mx.array: residual = hidden_states hidden_states = self.self_attn(self.layernorm_before(hidden_states), cos, sin) hidden_states = residual + self.lambda_1 * hidden_states residual = hidden_states hidden_states = self.mlp(self.layernorm_after(hidden_states)) return residual + self.lambda_2 * hidden_states
class VisionMerger(nn.Module): def __init__(self, args: VisionArgs, text_hidden_size: int): super().__init__() dims = args.adapter_merge_size**2 * args.hidden_size hidden, bias = args.projection_hidden_dim, args.projector_bias self.linear_1 = nn.Linear(dims, hidden, bias=bias) self.linear_2 = nn.Linear(hidden, text_hidden_size, bias=bias)
def __call__(self, image_features: mx.array) -> mx.array: return self.linear_2(_precise_gelu(self.linear_1(image_features)))
class VisionModel(nn.Module): def __init__(self, args: VisionArgs, text_hidden_size: int): super().__init__() self.args = args self.embeddings = VisionEmbeddings(args) self.pre_layernorm = nn.LayerNorm(args.hidden_size, eps=args.layer_norm_eps) self.rotary_emb = VisionRotaryEmbedding(args) self.layers = [VisionEncoderLayer(args) for _ in range(args.num_hidden_layers)] self.merger = VisionMerger(args, text_hidden_size)
def __call__(self, pixel_values: mx.array) -> mx.array: C, H, W = pixel_values.shape p, m = self.args.native_patch_size, self.args.adapter_merge_size if H % (p * m) or W % (p * m): raise ValueError(f"Image size {H}x{W} is not a multiple of {p * m}.") rows, cols = H // (p * m), W // (p * m) patches = pixel_values.transpose(1, 2, 0).reshape(rows, m, p, cols, m, p, C) # The merge blocks in raster order, then the patches of each block. patches = patches.transpose(0, 3, 1, 4, 2, 5, 6).reshape(-1, p * p * C) dtype = self.embeddings.patch_embedding.weight.dtype hidden_states = self.embeddings(patches.astype(dtype), rows * m, cols * m) hidden_states = self.pre_layernorm(hidden_states)
row, col = _grid_positions(rows * m, cols * m, m) zero = mx.zeros((1,), dtype=row.dtype) cos, sin = self.rotary_emb( mx.concatenate([zero, row + 1]), mx.concatenate([zero, col + 1]) ) for layer in self.layers: hidden_states = layer(hidden_states, cos, sin) patch_states = hidden_states[1:].reshape(rows * cols, -1) return self.merger(patch_states)
# =========================================================================# from mlx_lm/models/inkling2/checkpoint.py# =========================================================================# Copyright © 2026 Apple Inc.
import re
import mlx.core as mxfrom mlx.utils import tree_unflatten
from mlx_lm.models.switch_layers import SwitchLinear
__all__ = [ "sanitize",]
_NVFP4_E2M1_MAX = 6.0_NVFP4_E4M3_MAX = 448.0
_RENAMES = [ (r"^model\.llm\.unembed\.", "lm_head."), (r"^model\.llm\.embed\.", "model.language_model.embed_tokens."), (r"^model\.llm\.", "model.language_model."), (r"\.attn_res\.mlp_queries\.(\d+)$", r".layers.\1.mlp_input.query"), (r"\.attn_res\.output_query$", ".final_input.query"), (r"\.attn\.wq_du\.", ".self_attn.q_proj."), (r"\.attn\.wk_dv\.", ".self_attn.k_proj."), (r"\.attn\.wv_dv\.", ".self_attn.v_proj."), (r"\.attn\.wr_du\.", ".self_attn.r_proj."), (r"\.attn\.wo_ud\.", ".self_attn.o_proj."), (r"\.attn\.gate_attn\.", ".self_attn.gate_proj."), (r"\.attn\.attn_sink_proj\.", ".self_attn.sink_proj."), (r"\.controllers\.attn\.", ".q_message_gate."), (r"\.controllers\.(k|v|mlp)\.", r".\1_message_gate."), (r"_message_gate\.down_weight$", "_message_gate.down_proj.weight"), (r"_message_gate\.forget_weight$", "_message_gate.forget_gate_proj.weight"), (r"_message_gate\.gain_weight$", "_message_gate.message_gate_proj.weight"), (r"\.attn\.", ".self_attn."), (r"\.attn_sconv\.", ".post_attention_convolution."), (r"\.mlp_sconv\.", ".post_mlp_convolution."), (r"sconv\.weight$", "sconv.conv1d.weight"), (r"convolution\.weight$", "convolution.conv1d.weight"), (r"sconv\.static_w$", "sconv.static_weight"), (r"sconv\.weight_proj$", "sconv.weight_proj.weight"), (r"\.mlp_norm\.", ".post_attention_layernorm."), (r"\.attn_norm\.", ".input_layernorm."), (r"\.(q|k|v)_input_norm\.", r".\1_input_layernorm."), (r"\.mlp\.gate\.bias$", ".mlp.gate.e_score_correction_bias"), (r"^model\.visual\.backbone\.ln_pre\.", "model.vision_tower.pre_layernorm."), (r"^model\.visual\.backbone\.", "model.vision_tower."), (r"^model\.visual\.proj_in\.", "model.vision_tower.merger.linear_1."), (r"^model\.visual\.proj_out\.", "model.vision_tower.merger.linear_2."), (r"embeddings\.position_embedding$", "embeddings.position_embedding.weight"), (r"(vision_tower\.layers\.\d+)\.ln_1\.", r"\1.layernorm_before."), (r"(vision_tower\.layers\.\d+)\.ln_2\.", r"\1.layernorm_after."), (r"(vision_tower\.layers\.\d+)\.mlp\.c_fc\.", r"\1.mlp.fc1."), (r"(vision_tower\.layers\.\d+)\.mlp\.c_proj\.", r"\1.mlp.fc2."), (r"(vision_tower\.layers\.\d+)\.ls_(\d)\.gamma$", r"\1.lambda_\2"),]
def _rename(key: str) -> str: if m := re.match(r"model\.llm\.attn_res\.attn_queries\.(\d+)$", key): # Layer 0 has no attention input, so query i is for layer i + 1. layer = int(m.group(1)) + 1 return f"model.language_model.layers.{layer}.attention_input.query" for pattern, replacement in _RENAMES: key = re.sub(pattern, replacement, key) return key
def sanitize(model, weights: dict[str, mx.array]) -> dict[str, mx.array]: experts = re.compile(r"^(.+\.mlp\.experts)\.(w13|w2)_weight(\w*)$") amax, denominator = {}, {} message_queries = {} sanitized = {} for k, v in weights.items(): if k.startswith(("model.llm.", "model.visual.")): k = _rename(k) if k.endswith("conv1d.weight"): v = v.swapaxes(1, 2) if k.startswith("model.vision_tower.") and model.args.vision is None: continue if k.endswith(("cross_pass_queries", "cross_pass_kv_queries")): message_queries["kv" if "_kv_" in k else "q"] = v continue if k.endswith( ( ".mlp.gate.weight", ".forget_gate_proj.weight", ".message_gate_proj.weight", ) ): v = v.astype(mx.float32) elif m := experts.match(k): prefix, which, suffix = m.groups() name = f"{prefix}.{'gate_up_proj' if which == 'w13' else 'down_proj'}" if suffix == "_amax": amax[name] = v elif suffix == "_outer_scale_denominator": denominator[name] = v elif suffix == "_scale": sanitized[f"{name}.scales"] = v else: sanitized[f"{name}.weight"] = v.view(mx.uint32) continue sanitized[k] = v
if message_queries: # The checkpoint has [query, mlp] and [key, value] rows per looped layer. dims = message_queries["q"].shape[-1] q = message_queries["q"].reshape(-1, 2, dims) kv = message_queries["kv"].reshape(-1, 2, dims) query = mx.concatenate([q[:, :1], kv, q[:, 1:]], axis=1) sanitized["model.language_model.message_input.query"] = query
# Pipeline stages can miss the files of the other layers. for name in amax.keys() & denominator.keys(): scale = _NVFP4_E2M1_MAX * _NVFP4_E4M3_MAX scale = scale / denominator[name].astype(mx.float32) sanitized[f"{name}.global_scale"] = amax[name].astype(mx.float32) * scale
# mlx-lm does not read this quantization config, so set the experts here. modes = {(4, 16): "nvfp4", (4, 32): "mxfp4", (8, 32): "mxfp8"} quantized = [] for path, module in model.named_modules(): scales = sanitized.get(f"{path}.scales") if not isinstance(module, SwitchLinear) or scales is None: continue if scales.dtype != mx.uint8: # Float scales: affine output (RCO / oQ). ``load_model`` builds the # quantized carrier from config["quantization"] via nn.quantize(), # so there is nothing to do here. continue in_dims = module.weight.shape[-1] group_size = in_dims // scales.shape[-1] bits = sanitized[f"{path}.weight"].shape[-1] * 32 // in_dims if (bits, group_size) not in modes: continue ql = module.to_quantized( group_size, bits, mode=modes[bits, group_size], global_scale=f"{path}.global_scale" in sanitized, ) quantized.append((path, ql)) if quantized: model.update_modules(tree_unflatten(quantized)) return sanitized
# =========================================================================# from mlx_lm/models/inkling2/model.py# =========================================================================# Copyright © 2026 Apple Inc.
from typing import Any, Callable
import mlx.core as mxfrom mlx import nnfrom mlx.nn.layers.distributed import shard_linear
from mlx_lm.models.cache import ArraysCache, CacheList, KVCache, RotatingKVCache
__all__ = [ "Inkling2Model", "Model", "TextModel",]
class TextModel(PipelineMixin, nn.Module): def __init__(self, args: TextArgs): super().__init__() self.args = args self.embed_tokens = nn.Embedding(args.vocab_size, args.hidden_size) # Not in embed_tokens as in transformers, so that it can be quantized. self.embed_norm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps) self.layers = [ ( SlidingDecoderLayer(args, i) if i in args.local_layer_ids else FullDecoderLayer(args, i) ) for i in range(args.num_hidden_layers) ] self.final_input = BlockAttentionResidual(args.hidden_size) self.norm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps) if args.loop_config is not None: self.message_input = MessageInput(args.hidden_size, len(args.loop_core))
def embed(self, inputs: mx.array) -> mx.array: return self.embed_norm(self.embed_tokens(inputs))
@property def layer_visits(self) -> list[DecoderLayer]: if self.args.loop_config is None: return self.pipeline_layers core = self.args.loop_core passes = self.args.loop_config["num_passes"] layers = self.layers return ( layers[: core.start] + layers[core.start : core.stop] * passes + layers[core.stop :] )
def pipeline(self, group, split=None) -> None: if self.args.loop_config is not None: raise ValueError("Pipeline parallel does not support looped models.") super().pipeline(group, split)
def _run_loop(self, hidden_states, cache, conv_mask): core = self.args.loop_core caches = iter(cache)
def run(layers, hidden_states, block_states, bank=None): for i, layer in enumerate(layers): messages = None if bank is None else self.message_input(bank, i) hidden_states, block_states = layer( hidden_states, block_states, cache=next(caches), conv_mask=conv_mask, messages=messages, ) return hidden_states, block_states
prelude = run(self.layers[: core.start], hidden_states, None) hidden_states, block_states = prelude for loop_pass in range(self.args.loop_config["num_passes"]): bank = None if loop_pass > 0: bank = ( block_states[prelude[1].shape[0] + 1 :], unweighted_rms_norm(hidden_states.astype(mx.float32)), ) hidden_states, block_states = prelude hidden_states, block_states = run( self.layers[core.start : core.stop], hidden_states, block_states, bank ) return run(self.layers[core.stop :], hidden_states, block_states)
def __call__( self, inputs: mx.array, cache: list[Any] | None = None, input_embeddings: mx.array | None = None, ) -> mx.array: if input_embeddings is None: input_embeddings = self.embed(inputs) hidden_states = input_embeddings dtype = hidden_states.dtype
layers = self.pipeline_layers if cache is None: cache = [None] * len(self.layer_visits) conv_mask = None if cache[0] is not None: conv_mask = cache[0][1].make_mask(hidden_states.shape[1])
rank, size = self.pipeline_rank, self.pipeline_size block_states = None if rank < size - 1: num_blocks = -(-self.start_idx // self.args.n_layers_per_attn_res_block) states = mx.zeros((num_blocks + 1, *hidden_states.shape), mx.float32) states = mx.distributed.recv_like(states, rank + 1) hidden_states, block_states = states[0].astype(dtype), states[1:]
if self.args.loop_config is None: for layer, c in zip(layers, cache): hidden_states, block_states = layer( hidden_states, block_states, cache=c, conv_mask=conv_mask ) else: hidden_states, block_states = self._run_loop( hidden_states, cache, conv_mask )
if rank != 0: states = mx.concatenate( [hidden_states.astype(mx.float32)[None], block_states] ) states = mx.distributed.send(states, (rank - 1) % size) if cache[-1] is not None: kv_cache = cache[-1][0] kv_cache.keys = mx.depends(kv_cache.keys, states) # Only the output of rank 0 is used. hidden_states = states[0].astype(dtype) else: normed_states = unweighted_rms_norm(hidden_states.astype(mx.float32)) hidden_states = self.final_input(block_states, normed_states)[..., 0, :] hidden_states = self.norm(hidden_states).astype(dtype)
if size > 1: batch = hidden_states.shape[0] hidden_states = mx.distributed.all_gather(hidden_states)[:batch] return hidden_states
class Inkling2Model(nn.Module): def __init__(self, args: ModelArgs): super().__init__() self.language_model = TextModel(args.text) if args.vision is not None: self.vision_tower = VisionModel(args.vision, args.text.hidden_size)
# mlx_lm.utils pipelines model.model with these. @property def layers(self) -> list[DecoderLayer | None]: return self.language_model.layers
@property def start_idx(self) -> int: return self.language_model.start_idx
@property def end_idx(self) -> int | None: return self.language_model.end_idx
def pipeline(self, group, split=None) -> None: self.language_model.pipeline(group, split)
class Model(nn.Module): def __init__(self, args: ModelArgs): super().__init__() self.args = args self.model_type = args.model_type self.model = Inkling2Model(args) text = args.text self.lm_head = nn.Linear(text.hidden_size, text.vocab_size, bias=False) self.sharding_group = None
def encode_image(self, pixel_values: mx.array | list[mx.array]) -> mx.array: """pixel_values: one image (num_channels, H, W) or a list of images of any size. Returns the rows of the image tokens of all images.""" if isinstance(pixel_values, mx.array) and pixel_values.ndim == 3: pixel_values = [pixel_values] assert len(pixel_values), "No images." return mx.concatenate([self.model.vision_tower(p) for p in pixel_values])
def embed_inputs( self, inputs: mx.array, *, pixel_values: mx.array | list[mx.array] | None = None, ) -> mx.array: inputs_embeds = self.model.language_model.embed(inputs) if pixel_values is not None: image_features = self.encode_image(pixel_values) inputs_embeds = splice( inputs_embeds, inputs, rows=image_features, token_id=self.args.image_token_id, ) return inputs_embeds
def __call__( self, inputs: mx.array, cache: list[Any] | None = None, input_embeddings: mx.array | None = None, pixel_values: mx.array | list[mx.array] | None = None, ) -> mx.array: if pixel_values is not None: assert input_embeddings is None, "Pass pixel_values or input_embeddings." input_embeddings = self.embed_inputs(inputs, pixel_values=pixel_values) hidden_states = self.model.language_model( inputs, cache=cache, input_embeddings=input_embeddings ) logits = self.lm_head(hidden_states) if self.sharding_group is not None: logits = gather_last_axis(logits, self.sharding_group) text = self.args.text softcap = text.final_logit_softcapping logits = logits.astype(mx.float32) logits = mx.tanh(logits / softcap) * softcap return logits[..., : text.unpadded_vocab_size]
def sanitize(self, weights: dict[str, mx.array]) -> dict[str, mx.array]: return sanitize(self, weights)
def shard(self, group: mx.distributed.Group | None = None) -> None: group = group or mx.distributed.init() N, r = group.size(), group.rank() text = self.args.text for n_kv_heads in (text.num_key_value_heads, text.swa_num_key_value_heads): assert ( n_kv_heads % N == 0 ), f"group size {N} must divide num_key_value_heads {n_kv_heads}" assert ( text.vocab_size % N == 0 ), f"group size {N} must divide vocab_size {text.vocab_size}"
def part(w: mx.array, axis: int) -> mx.array: return mx.contiguous(mx.split(w, N, axis=axis)[r])
self.lm_head = shard_linear(self.lm_head, "all-to-sharded", group=group) self.sharding_group = group for layer in self.layers: attn = layer.self_attn for name in ( "q_proj", "k_proj", "v_proj", "r_proj", "gate_proj", "sink_proj", ): proj = shard_linear(getattr(attn, name), "all-to-sharded", group=group) setattr(attn, name, proj) attn.o_proj = shard_linear(attn.o_proj, "sharded-to-all", group=group) attn.q_l2_clip.scale = part(attn.q_l2_clip.scale, 0) attn.rel_l2_clip.scale = part(attn.rel_l2_clip.scale, 0) for conv in (attn.k_sconv, attn.v_sconv): if isinstance(conv, ShortConvolution): conv.conv1d.weight = part(conv.conv1d.weight, 0) conv.conv1d.groups //= N else: conv.static_weight = part(conv.static_weight, 1) conv.weight_proj = shard_linear( conv.weight_proj, "all-to-sharded", group=group ) conv.num_heads //= N attn.num_heads //= N attn.num_key_value_heads //= N
layer.mlp.sharding_group = group experts = layer.mlp.experts shard_experts_inplace(experts.gate_up_proj, "all-to-sharded", group) shard_experts_inplace(experts.down_proj, "sharded-to-all", group)
@property def quant_predicate(self) -> Callable[[str, nn.Module], bool]:
def predicate(path: str, module: nn.Module) -> bool: return not path.startswith("model.vision_tower.") and ( "_message_gate." not in path )
return predicate
@property def cast_predicate(self) -> Callable[[str], bool]:
def predicate(k: str) -> bool: return not k.endswith( ( ".query", ".mlp.gate.weight", ".mlp.gate.e_score_correction_bias", ".forget_gate_proj.weight", ".message_gate_proj.weight", ) )
return predicate
@property def layers(self) -> list[DecoderLayer]: return self.model.language_model.pipeline_layers
def make_cache(self) -> list[CacheList]: window = self.args.text.sliding_window_size return [ CacheList( ( RotatingKVCache(max_size=window) if isinstance(layer, SlidingDecoderLayer) else KVCache() ), ArraysCache(4), ) for layer in self.model.language_model.layer_visits ]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788# Copyright © 2026 Apple Inc.
"""Image processor of Inkling 2."""
import mathfrom dataclasses import dataclassfrom typing import BinaryIO, ClassVar, Sequence
import mlx.core as mximport numpy as np
__all__ = [ "IMAGE_TOKEN", "Processor",]
IMAGE_TOKEN = "<|unused_200054|>"
def _composite_alpha(rgba: np.ndarray) -> np.ndarray: height, width, _ = rgba.shape y, x = np.ogrid[:height, :width] background = np.where((x // 8 + y // 8) % 2 == 0, 204, 153)[..., None] rgb, alpha = rgba[..., :3].astype(np.int32), rgba[..., 3:].astype(np.int32) blended = (rgb * alpha + background * (255 - alpha) + 127) // 255 return blended.astype(np.uint8)
@dataclass(frozen=True)class Processor: image_token: ClassVar[str] = IMAGE_TOKEN
block_size: int = 40 image_mean: tuple[float, float, float] = (0.5, 0.5, 0.5) image_std: tuple[float, float, float] = (0.5, 0.5, 0.5)
@classmethod def from_config(cls, config: dict) -> "Processor": vision = config.get("vision_config") if not vision: raise ValueError("The model config has no vision_config.") patch_size = vision.get("native_patch_size", 20) merge_size = vision.get("adapter_merge_size", 2) return cls(block_size=patch_size * merge_size)
def load_image(self, fp: str | BinaryIO) -> np.ndarray: """A uint8 (H, W, 3) image. As the reference, transparent pixels are put on a gray checkerboard.""" from PIL import Image
with Image.open(fp) as image: if not image.has_transparency_data: return np.asarray(image.convert("RGB")) rgba = np.asarray(image.convert("RGBA")) return _composite_alpha(rgba)
def preprocess_image(self, image: np.ndarray) -> tuple[mx.array, int]: assert image.ndim == 3 and image.shape[-1] == 3, "Images must be (H, W, 3)." assert image.dtype == np.uint8, "Images must be uint8." height, width, _ = image.shape rows = math.ceil(height / self.block_size) cols = math.ceil(width / self.block_size) # As the reference, the padding is -1 on the 0-255 scale. x = np.full( (rows * self.block_size, cols * self.block_size, 3), -1.0, np.float32 ) x[:height, :width] = image mean = np.array(self.image_mean, dtype=np.float32) std = np.array(self.image_std, dtype=np.float32) x = (x * np.float32(1 / 255) - mean) / std return mx.array(x.transpose(2, 0, 1)), rows * cols
def __call__( self, text: str, *, images: Sequence[np.ndarray] ) -> tuple[str, dict[str, list[mx.array]]]: parts = text.split(IMAGE_TOKEN) if len(parts) - 1 != len(images): raise ValueError( f"The text has {len(parts) - 1} {IMAGE_TOKEN} " f"for {len(images)} images." ) pixel_values = [] expanded = [parts[0]] for image, part in zip(images, parts[1:], strict=True): pixels, num_tokens = self.preprocess_image(image) expanded += [IMAGE_TOKEN * num_tokens, part] pixel_values.append(pixels) return "".join(expanded), {"pixel_values": pixel_values}123version https://git-lfs.github.com/spec/v1oid sha256:5daff796ddfc15b96319a74b87f4afe2a7430df6774bae61e923bcca3def0641size 5333707043123version https://git-lfs.github.com/spec/v1oid sha256:f4d71fd60ac9c186bd7e5567e0be6023beff538f25b14b34ffc267c67cbc2613size 5084149934123version https://git-lfs.github.com/spec/v1oid sha256:47ee9f7e0dd0617bcf947fec1f0c249bbf3cfbbf01fce73ff3f88d08bf981c67size 5360338436123version https://git-lfs.github.com/spec/v1oid sha256:16930eb5e9bee3dbbb8d85b4d7912b80fa6251aca0df0c25699b3db700b479e5size 379029991412345678910111213141516171819202122232425{ "image_processor": { "do_convert_rgb": true, "do_normalize": true, "do_rescale": true, "image_mean": [ 0.5, 0.5, 0.5 ], "image_processor_type": "Inkling2ImageProcessor", "image_std": [ 0.5, 0.5, 0.5 ], "rescale_factor": 0.00392156862745098, "size": { "height": 40, "width": 40 } }, "image_token": "<|unused_200054|>", "processor_class": "Inkling2Processor"}123456789101112131415161718192021{ "additional_special_tokens": [ "<|endoftext|>", "<|message_user|>", "<|message_model|>", "<|message_system|>", "<|message_tool|>", "<|content_text|>", "<|content_image|>", "<|content_model_end_sampling|>", "<|content_thinking|>", "<|end_message|>", "<|content_tool_error|>", "<|content_xml|>", "<|begin_of_text|>", "<|content_invoke_tool_json|>", "<|content_invoke_tool_text|>" ], "eos_token": "<|content_model_end_sampling|>", "pad_token": "<|endoftext|>"}123version https://git-lfs.github.com/spec/v1oid sha256:f170372dd655728909228220d77cf6b8104a59f38a91262a7d2c4027906ec0d8size 3386494123version https://git-lfs.github.com/spec/v1oid sha256:7f332727f9a3f093dd452a39cc978e6757627e5dad1b0673aa4e75174f236dd6size 26178678123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384{ "backend": "tokenizers", "begin_of_text": "<|begin_of_text|>", "clean_up_tokenization_spaces": false, "content_image": "<|content_image|>", "content_invoke_tool_json": "<|content_invoke_tool_json|>", "content_invoke_tool_text": "<|content_invoke_tool_text|>", "content_model_end_sampling": "<|content_model_end_sampling|>", "content_text": "<|content_text|>", "content_thinking": "<|content_thinking|>", "content_tool_error": "<|content_tool_error|>", "content_xml": "<|content_xml|>", "end_message": "<|end_message|>", "endoftext": "<|endoftext|>", "eos_token": "<|content_model_end_sampling|>", "fix_mistral_regex": false, "is_local": true, "local_files_only": false, "message_model": "<|message_model|>", "message_system": "<|message_system|>", "message_tool": "<|message_tool|>", "message_user": "<|message_user|>", "model_max_length": 1048576, "model_specific_special_tokens": { "begin_of_text": "<|begin_of_text|>", "content_image": "<|content_image|>", "content_invoke_tool_json": "<|content_invoke_tool_json|>", "content_invoke_tool_text": "<|content_invoke_tool_text|>", "content_model_end_sampling": "<|content_model_end_sampling|>", "content_text": "<|content_text|>", "content_thinking": "<|content_thinking|>", "content_tool_error": "<|content_tool_error|>", "content_xml": "<|content_xml|>", "end_message": "<|end_message|>", "endoftext": "<|endoftext|>", "message_model": "<|message_model|>", "message_system": "<|message_system|>", "message_tool": "<|message_tool|>", "message_user": "<|message_user|>" }, "pad_token": "<|endoftext|>", "response_template": { "defaults": { "role": "assistant" }, "fields": { "content": { "close": "<|end_message|>", "content": "text", "content_args": { "strip": false }, "join": "", "open_pattern": "(?:<\\|message_model\\|>[^<]*)?<\\|content_(?:text|tool_error|invoke_tool_text)\\|>", "repeats": true }, "reasoning_content": { "close": "<|end_message|>", "content": "text", "content_args": { "strip": false }, "join": "", "open_pattern": "(?:<\\|message_model\\|>[^<]*)?<\\|content_thinking\\|>", "repeats": true }, "tool_calls": { "close": "<|end_message|>", "content": "json", "open_pattern": "(?:<\\|message_model\\|>[^<]*)?<\\|content_invoke_tool_json\\|>", "repeats": true, "transform": { "function": { "arguments": "{content.args}", "name": "{content.name}" }, "type": "function" } } }, "start_anchor_pattern": "<\\|end_message\\|>|<\\|content_model_end_sampling\\|>" }, "tokenizer_class": "TokenizersBackend"}.gitattributes+3
LICENSEAdded+233
NOTICEAdded+14
README.mdAdded+127
__pycache__/inkling2_loop.cpython-312.pycAdded+3
chat_template.jinjaAdded+137
config.jsonAdded+129
generation_config.jsonAdded+6
inkling2_loop.pyAdded+2003
inkling2_processor.pyAdded+88
model-00001-of-00004.safetensorsAdded+3
model-00002-of-00004.safetensorsAdded+3
model-00003-of-00004.safetensorsAdded+3
model-00004-of-00004.safetensorsAdded+3
model.safetensors.index.jsonAdded
processor_config.jsonAdded+25
special_tokens_map.jsonAdded+21
tiktoken/tokenizer.modelAdded+3
tokenizer.jsonAdded+3
tokenizer_config.jsonAdded+84
ukisai-banner.pngAdded

Large File Pointer Details
- SHA256: ab32bde5cf1390afb9476954ad2199c19298f2f0149d2579b15de91682fe4f7f
- Pointer size: 131 Bytes
- Size of remote file: 391 kB