Image-Text-to-Text
MLX
Safetensors
inkling2_loop
quantized
4-bit precision
affine
inkling
conversational
Run this model with HF Jobs
Run ukisai/Swift-Inkling-2-Mini-MLX-4bit 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-4bit. 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-4bit 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-4bit. 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-4bit 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-4bit 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-4bit") config = load_config("ukisai/Swift-Inkling-2-Mini-MLX-4bit") # 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-4bit 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-4bit"
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-4bit" } ] } } }Run Pi
# Start Pi in your project directory: pi
- Hermes Agent
How to use ukisai/Swift-Inkling-2-Mini-MLX-4bit 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-4bit"
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-4bit
Run Hermes
hermes
- Atomic Chat
- OpenClaw
How to use ukisai/Swift-Inkling-2-Mini-MLX-4bit 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-4bit"
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-4bit" \ --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"
File size: 75,677 Bytes
913b79e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 | # 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 visits
from 24 physical layers). The published checkpoint stores its routed experts as
NVFP4 (layers 0-19) and MXFP8 (layers 20-23); `sanitize` reconstructs
the 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 math
import re
from dataclasses import dataclass
from functools import partial
from typing import Any, Callable
import mlx.core as mx
from mlx import nn
from mlx.nn.layers.distributed import shard_linear, sum_gradients
from mlx.utils import tree_unflatten
from mlx_lm.kernels.expert_routing import expert_routing
from mlx_lm.models.base import BaseModelArgs
from 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_cache
def 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",
]
@dataclass
class 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))
@dataclass
class 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)
@dataclass
class 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 math
from functools import partial
from typing import Any
import mlx.core as mx
from mlx import nn
from mlx.nn.layers.distributed import sum_gradients
from mlx_lm.kernels.expert_routing import expert_routing
from mlx_lm.models.switch_layers import SwitchLinear, _gather_sort, _scatter_unsort
from 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 mx
from 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 mx
from 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 mx
from mlx import nn
from 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
]
|