ChengyiX commited on
Commit
4606829
·
verified ·
1 Parent(s): 311f19a

Initial release of mlx-agent-tools (v1.0.0)

Browse files
.gitignore ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ .DS_Store
2
+ __pycache__/
3
+ *.pyc
4
+ *.egg-info/
5
+ dist/
6
+ build/
CITATION.cff ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cff-version: 1.2.0
2
+ message: "If you use this toolkit in your research or deployment, please cite it as below."
3
+ title: "MLX Agent Tools: Reusable Acceleration, Quantization, and Serving Utilities for Apple Silicon"
4
+ authors:
5
+ - family-names: Xu
6
+ given-names: Chengyi
7
+ orcid: "https://orcid.org/0009-0008-1277-6670"
8
+ - name: Nexora
9
+ version: 1.0.0
10
+ date-released: 2026-10-25
11
+ type: software
12
+ url: "https://github.com/chengyixu/mlx-agent-tools"
13
+ license: MIT
14
+ abstract: "Open-source Python utilities for bounded-memory CPU quantization, MTP sidecar extraction, speculative decoding measurement, and safe local model serving on Apple Silicon."
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Chengyi Xu and Nexora
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MLX Agent Tools
2
+
3
+ **Reusable acceleration, quantization, conversion, and serving utilities for Apple Silicon AI agents.**
4
+
5
+ Developed by **Chengyi Xu and Nexora** — **Nexora Research**
6
+
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
8
+ [![Tests](https://img.shields.io/badge/tests-24%20passed-brightgreen.svg)](tests/)
9
+
10
+ ---
11
+
12
+ ## Overview
13
+
14
+ Deploying large language and multimodal models (e.g. Qwen, Coder390, Fable) on Apple Silicon unified memory faces strict memory and architectural constraints. Standard tooling often causes out-of-memory kernel panics during quantization, corrupts speculative weights during format translation, or fails under background swap.
15
+
16
+ `mlx-agent-tools` provides five verified, zero-regression utility modules to overcome these hurdles:
17
+
18
+ | Module | Purpose | Key Property |
19
+ |---|---|---|
20
+ | `stream_convert.py` | Bounded CPU streaming affine 4-bit quantizer | Converts 27B+ checkpoints in 128-row chunks; peak RSS ≤ 3.08 GB. |
21
+ | `separate_mtp.py` | MTP sidecar extractor & repackager | Separates embedded MTP tensors from trunk weights to fix RMSNorm double-gain corruption. |
22
+ | `inference_window.py` | Exclusive inference window harness | Manages single-large-model transitions, process locks, and multi-turn TTFT measurements. |
23
+ | `cpu_checkpoint.py` | Bounded checkpoint row reader | Reads partial tensor slices directly from disk into CPU memory without loading the full model. |
24
+ | `redacting_log.py` | Zero-leakage credential log stream | Redacts API keys and secrets across split chunks before stdout/log persistence. |
25
+
26
+ ---
27
+
28
+ ## Installation
29
+
30
+ ```bash
31
+ pip install -e .
32
+ ```
33
+
34
+ Requires Python ≥ 3.10 and `mlx` ≥ 0.22.0.
35
+
36
+ ---
37
+
38
+ ## Usage
39
+
40
+ ### 1. Bounded Streaming Quantization (`stream_convert.py`)
41
+
42
+ Quantize large checkpoints to MLX affine 4-bit format entirely on CPU with bounded memory:
43
+
44
+ ```python
45
+ from mlx_agent_tools import stream_convert
46
+
47
+ # Converts shard by shard in bounded row chunks
48
+ stream_convert(
49
+ source_dir="path/to/bf16_model",
50
+ output_dir="path/to/mlx_q4_model",
51
+ hashes={"model-00001-of-00004.safetensors": {"sha256": "...", "size": 12345678}},
52
+ row_chunk=128
53
+ )
54
+ ```
55
+
56
+ ### 2. MTP Sidecar Separation (`separate_mtp.py`)
57
+
58
+ When MLX models embed `mtp.*` weights in primary trunk shards, `mlx-lm` erroneously applies an extra +1.0 shift to already-normalized RMSNorm weights. `separate_mtp` extracts MTP weights into a dedicated `mtp.safetensors` container while preserving exact trunk bytes:
59
+
60
+ ```python
61
+ from mlx_agent_tools import separate_mtp
62
+
63
+ separate_mtp(
64
+ source_dir="path/to/embedded_mtp_model",
65
+ output_dir="path/to/clean_model"
66
+ )
67
+ ```
68
+
69
+ ### 3. CPU-Bounded Checkpoint Inspection (`cpu_checkpoint.py`)
70
+
71
+ Read exact weight rows from large safetensors files without allocating GPU memory:
72
+
73
+ ```python
74
+ from mlx_agent_tools import rows
75
+
76
+ # Read rows 0..128 of an embedding table
77
+ tensor_slice = rows("path/to/model", "model.language_model.embed_tokens.weight", start=0, end=128)
78
+ ```
79
+
80
+ ### 4. Zero-Leakage Credential Redaction (`redacting_log.py`)
81
+
82
+ Wrap model server process output streams to guarantee API tokens never reach logs:
83
+
84
+ ```python
85
+ import sys
86
+ from mlx_agent_tools import SecretLogStream
87
+
88
+ # Safe streaming wrapper
89
+ safe_stdout = SecretLogStream(sys.stdout, secret="sk-live-secret-token")
90
+ safe_stdout.write("Serving model with key sk-live-secret-token initialized.\n")
91
+ # Output: Serving model with key [redacted] initialized.
92
+ ```
93
+
94
+ ---
95
+
96
+ ## Test Suite
97
+
98
+ All tools are accompanied by a comprehensive test suite (24 unit tests) covering bounded allocation, byte-exactness, SHA-256 verification, and error handling:
99
+
100
+ ```bash
101
+ python3 -m unittest discover -s tests -p "test_*.py"
102
+ ```
103
+
104
+ ---
105
+
106
+ ## Citation
107
+
108
+ ```bibtex
109
+ @software{xu2026mlxagenttools,
110
+ title = {MLX Agent Tools: Reusable Acceleration, Quantization, and Serving Utilities for Apple Silicon},
111
+ author = {Xu, Chengyi and {{Nexora}}},
112
+ year = {2026},
113
+ month = oct,
114
+ url = {https://github.com/chengyixu/mlx-agent-tools}
115
+ }
116
+ ```
117
+
118
+ ---
119
+
120
+ ## License
121
+
122
+ MIT License. Copyright (c) 2026 Chengyi Xu and Nexora.
SHA256SUMS ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ e37da5ef1db7e8c5c699b10ddbc265a8590306f7de4d08a0a3afbaa85bb4e216 .gitignore
2
+ 6c9adcf659451a8a032e515c894c92557e0436a8aea1c1503ceea50b740756ec CITATION.cff
3
+ e70e205e628186f1598e0a084b00be806d4d760335af334b8de112b1c3aff3ee LICENSE
4
+ b116157d4f5225f06be99e7efa048295324ca9c35a456b47ee37cc31351f3e6e README.md
5
+ a19b0a12dd0d6ecf46fc4ac9ca2561c3ab80e0a94d04be874a7c696442980c27 mlx_agent_tools/__init__.py
6
+ adc049ad5285b362e553536930308f75e0981c26e86e58e0731df6bb1ef2dd76 mlx_agent_tools/cpu_checkpoint.py
7
+ a9f0657a5ae21f663640a0be4577d0aab0997a52935c4f88f552af0ed2a60042 mlx_agent_tools/inference_window.py
8
+ bdeb2cb3e01338b9cfdb2a5fac7f021265dda62d81d75b952136d38839d4b953 mlx_agent_tools/raw/upstream/language.py
9
+ 7c0e360a35e1f5d3819677cd6f7e4d7349f4f3dd2fad5fc8f1e374bd514e8f1b mlx_agent_tools/raw/upstream/qwen3_5.py
10
+ bd1bfe7ce6ea40f364b23ff8b9e9399153349a55bef9870477ba2fddba1e2378 mlx_agent_tools/redacting_log.py
11
+ 3cfc1d6da71929feb26bbaa425fdd087b20530c812ece4f97f0ecaa1b46d334c mlx_agent_tools/separate_mtp.py
12
+ 0a3e4c59213cf3875c231b33b8c35e1009906697232fa108c004fbdaaf7a1a05 mlx_agent_tools/stream_convert.py
13
+ 2de12a01b7c70994d526fefe58dad346cb1359792cbacf06d2929ec8411095b8 pyproject.toml
14
+ 9bb5e4b1886651ea23a3d9ee9d1eb738789bc41ec119c3598c142321b48b05e9 tests/test_cpu_checkpoint.py
15
+ 9daeb68ba345573e4d1ab4996a85988674e416ad5dca76bf21eebeab86dadbae tests/test_inference_window.py
16
+ 6024a6dd52c55b1c285e0623e5ed4954f1cce0adc7d3059a7b1b05f77d2dfc92 tests/test_redacting_log.py
17
+ ccecba97ee180b4939169e2e4fdc1a1fe153e42c9edfd9ef7c36844e1c2e837b tests/test_separate_mtp.py
18
+ 2ec2a3efec3ef001925a3067628f71f5f4a992e93f6791b29c303616402bb546 tests/test_stream_convert.py
mlx_agent_tools/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MLX Agent Tools: Reusable acceleration, quantization, conversion, and serving utilities for Apple Silicon."""
2
+ from __future__ import annotations
3
+
4
+ from .cpu_checkpoint import all_small, probes, rows
5
+ from .inference_window import external_accelerator_work, run_window, small_idle_llama
6
+ from .redacting_log import SecretLogStream
7
+ from .separate_mtp import prepare as separate_mtp
8
+ from .stream_convert import convert as stream_convert
9
+
10
+ __version__ = "1.0.0"
11
+ __all__ = [
12
+ "all_small",
13
+ "probes",
14
+ "rows",
15
+ "external_accelerator_work",
16
+ "run_window",
17
+ "small_idle_llama",
18
+ "SecretLogStream",
19
+ "separate_mtp",
20
+ "stream_convert",
21
+ ]
mlx_agent_tools/cpu_checkpoint.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bounded CPU tensor slices and arithmetic probes; not an inference benchmark.
2
+
3
+ Uses safetensors' slice contract; never loads a complete checkpoint or engine.
4
+ """
5
+ from __future__ import annotations
6
+ import argparse
7
+ import gc
8
+ import json
9
+ import math
10
+ from pathlib import Path
11
+ import time
12
+
13
+ import mlx.core as mx
14
+ import numpy as np
15
+ import torch
16
+ from safetensors import safe_open
17
+
18
+ ROOT = Path(__file__).resolve().parent
19
+ mx.set_default_device(mx.cpu)
20
+ torch.set_num_threads(2)
21
+
22
+
23
+ def rows(root, name, start, end, *, max_bytes=32 * 1024 * 1024):
24
+ if mx.default_device() != mx.cpu:
25
+ raise ValueError('Bounded checkpoint probes require CPU device')
26
+ root = Path(root).resolve()
27
+ mapping = json.loads((root / 'model.safetensors.index.json').read_text())['weight_map']
28
+ if name not in mapping:
29
+ raise ValueError('Missing checkpoint tensor: ' + name)
30
+ filename = mapping[name]
31
+ if Path(filename).name != filename:
32
+ raise ValueError('Unsafe checkpoint shard path')
33
+ path = (root / filename).resolve()
34
+ if path.parent != root:
35
+ raise ValueError('Checkpoint shard path escapes root')
36
+ with safe_open(path, framework='pt', device='cpu') as handle:
37
+ if name not in handle.keys():
38
+ raise ValueError('Index points at missing tensor: ' + name)
39
+ tensor = handle.get_slice(name)
40
+ shape = tensor.get_shape()
41
+ if not shape or not (0 <= start < end <= shape[0]):
42
+ raise ValueError('Invalid checkpoint row bounds')
43
+ # Conservative worst-case dtype width; guard before materialization.
44
+ if (end - start) * math.prod(shape[1:]) * 8 > max_bytes:
45
+ raise ValueError('Checkpoint slice exceeds memory bound')
46
+ value = tensor[start:end]
47
+ if value.dtype == torch.bfloat16:
48
+ return mx.array(value.view(torch.uint16).numpy()).view(mx.bfloat16)
49
+ return mx.array(value.numpy())
50
+
51
+
52
+ def all_small(root, name):
53
+ mapping = json.loads((Path(root) / 'model.safetensors.index.json').read_text())['weight_map']
54
+ with safe_open(Path(root) / mapping[name], framework='pt', device='cpu') as handle:
55
+ count = handle.get_slice(name).get_shape()[0]
56
+ return rows(root, name, 0, count)
57
+
58
+
59
+ def probes(output):
60
+ started = time.monotonic()
61
+ target, source = ROOT / 'target-affine4-g64', ROOT / 'source/BF16'
62
+ from mlx_vlm.models.qwen3_vl.vision import PatchEmbed
63
+ records = []
64
+ # Projection arithmetic is checked against an independent torch matmul of
65
+ # explicitly dequantized weights; this does not test end-to-end model quality.
66
+ for name, count in [
67
+ ('language_model.model.layers.0.linear_attn.in_proj_a.weight', 48),
68
+ ('language_model.model.layers.0.mlp.up_proj.weight', 8),
69
+ ('language_model.model.layers.31.self_attn.q_proj.weight', 8),
70
+ ('language_model.lm_head.weight', 8),
71
+ ]:
72
+ prefix = name.removesuffix('.weight')
73
+ q = rows(target, name, 0, count)
74
+ scale = rows(target, prefix + '.scales', 0, count)
75
+ bias = rows(target, prefix + '.biases', 0, count)
76
+ width = q.shape[1] * 8
77
+ x = (mx.arange(2 * width).reshape(2, width).astype(mx.float32) % 19 - 9) / 32
78
+ x = x.astype(mx.bfloat16)
79
+ # CPU BF16 quantized_matmul can accumulate/round differently from a
80
+ # float32 dequantized matmul. Keep that observation, but isolate packed
81
+ # layout correctness with matched float32 arithmetic, not a looser gate.
82
+ bf16_result = mx.quantized_matmul(x, q, scale, bias, transpose=True, group_size=64, bits=4)
83
+ xf, sf, bf = x.astype(mx.float32), scale.astype(mx.float32), bias.astype(mx.float32)
84
+ actual = mx.quantized_matmul(xf, q, sf, bf, transpose=True, group_size=64, bits=4)
85
+ dense = mx.dequantize(q, sf, bf, group_size=64, bits=4)
86
+ mx.eval(actual, dense, xf, bf16_result)
87
+ ref = torch.from_numpy(np.asarray(xf)) @ torch.from_numpy(np.asarray(dense)).T
88
+ want = mx.array(ref.numpy())
89
+ error = float(mx.max(mx.abs(actual - want)))
90
+ denominator = max(float(mx.max(mx.abs(want))), 1e-6)
91
+ bf16_error = float(mx.max(mx.abs(bf16_result.astype(mx.float32) - want)))
92
+ finite = bool(mx.all(mx.isfinite(actual)))
93
+ if not finite or error > 1e-4 * max(1., denominator):
94
+ raise ValueError('CPU float32 packed projection parity failed: ' + name)
95
+ records.append({'probe': 'quantized_projection', 'tensor': name, 'rows': count,
96
+ 'output_shape': list(actual.shape), 'finite': finite,
97
+ 'layout_parity_arithmetic_dtype': 'float32',
98
+ 'max_abs_error': error, 'max_abs_error_over_peak': error / denominator,
99
+ 'cpu_bf16_vs_float32_max_abs_error': bf16_error,
100
+ 'cpu_bf16_vs_float32_error_over_peak': bf16_error / denominator,
101
+ 'bf16_cpu_inference_parity_claimed': False})
102
+ del q, scale, bias, x, actual, dense, ref, want, xf, sf, bf, bf16_result
103
+ gc.collect()
104
+
105
+ # True source Conv3d vs native MLX PatchEmbed, with just 8 output channels.
106
+ config = json.loads((target / 'config.json').read_text())['vision_config']
107
+ original = rows(source, 'model.visual.patch_embed.proj.weight', 0, 8).astype(mx.float32)
108
+ converted = rows(target, 'vision_tower.patch_embed.proj.weight', 0, 8).astype(mx.float32)
109
+ bias = rows(target, 'vision_tower.patch_embed.proj.bias', 0, 8).astype(mx.float32)
110
+ patch = PatchEmbed(patch_size=config['patch_size'], temporal_patch_size=config['temporal_patch_size'],
111
+ in_channels=config['in_channels'], hidden_size=8)
112
+ patch.load_weights([('proj.weight', converted), ('proj.bias', bias)], strict=True)
113
+ pixels = mx.arange(3 * 2 * 16 * 16).astype(mx.float32).reshape(1, -1) / 4096
114
+ actual = patch(pixels)
115
+ ref = torch.nn.functional.conv3d(torch.from_numpy(np.asarray(pixels).reshape(1, 3, 2, 16, 16)),
116
+ torch.from_numpy(np.asarray(original)), torch.from_numpy(np.asarray(bias)),
117
+ stride=(2, 16, 16)).reshape(1, 8)
118
+ mx.eval(actual)
119
+ error = float(mx.max(mx.abs(actual - mx.array(ref.numpy()))))
120
+ if error > .001 or not bool(mx.all(mx.isfinite(actual))):
121
+ raise ValueError('Source/native vision patch arithmetic mismatch')
122
+ records.append({'probe': 'vision_patch_embed', 'output_channels': 8,
123
+ 'native_module': 'mlx_vlm.models.qwen3_vl.vision.PatchEmbed',
124
+ 'comparison': 'original-source torch Conv3d CPU', 'max_abs_error': error})
125
+
126
+ norm = all_small(target, 'language_model.model.layers.0.input_layernorm.weight').astype(mx.float32)
127
+ x = (mx.arange(norm.size).astype(mx.float32) % 17 - 8).reshape(1, -1) / 16
128
+ actual = mx.fast.rms_norm(x, norm, 1e-6)
129
+ refx = torch.from_numpy(np.asarray(x))
130
+ ref = refx * torch.rsqrt(refx.square().mean(dim=-1, keepdim=True) + 1e-6) * torch.from_numpy(np.asarray(norm))
131
+ mx.eval(actual)
132
+ error = float(mx.max(mx.abs(actual - mx.array(ref.numpy()))))
133
+ if error > .0001:
134
+ raise ValueError('CPU norm arithmetic mismatch')
135
+ records.append({'probe': 'rmsnorm', 'max_abs_error': error})
136
+
137
+ result = {'device': 'cpu', 'scope': 'bounded projection, vision patch and norm arithmetic only',
138
+ 'full_model_loaded': False, 'model_forward_or_answer': False,
139
+ 'inference_speed_measured': False, 'all_passed': True,
140
+ 'elapsed_s': time.monotonic() - started, 'probes': records}
141
+ output.write_text(json.dumps(result, indent=2) + '\n')
142
+ return result
143
+
144
+
145
+ if __name__ == '__main__':
146
+ parser = argparse.ArgumentParser()
147
+ parser.add_argument('--output', type=Path, required=True)
148
+ args = parser.parse_args()
149
+ print(json.dumps(probes(args.output), indent=2))
mlx_agent_tools/inference_window.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Foreground owned engine window; controller lock held until prior restore."""
2
+ from pathlib import Path
3
+ import argparse
4
+ import json
5
+ import os
6
+ import signal
7
+ import shlex
8
+ import http.client
9
+ import subprocess
10
+ import sys
11
+ import time
12
+
13
+ ROOT = Path(__file__).resolve().parents[2]
14
+ sys.path.insert(0, str(ROOT))
15
+ try:
16
+ import stack_controller
17
+ except ImportError:
18
+ stack_controller = None
19
+
20
+
21
+ def small_idle_llama(argv, *, query=None):
22
+ """Permit only a verified <=2GiB, <=8k idle loopback native server.
23
+
24
+ One-large-engine policy does not authorize stopping unrelated small apps.
25
+ Any missing/unknown ownership, model or processing fact remains blocking.
26
+ """
27
+ try:
28
+ def option(*names):
29
+ for name in names:
30
+ if name in argv:return argv[argv.index(name)+1]
31
+ return None
32
+ weight = Path(option('-m', '--model')).resolve()
33
+ host = option('--host')
34
+ port = int(option('--port'))
35
+ if host not in ('localhost', '127.0.0.1') or not 1 <= port <= 65535:
36
+ return False
37
+ if not weight.is_file() or weight.stat().st_size > 2 * 1024**3:
38
+ return False
39
+ def request(port, path):
40
+ connection = http.client.HTTPConnection('127.0.0.1', port, timeout=2)
41
+ try:
42
+ connection.request('GET', path)
43
+ response = connection.getresponse()
44
+ if response.status != 200:return None
45
+ return json.loads(response.read())
46
+ finally:connection.close()
47
+ get = query or request
48
+ props, slots = get(port, '/props'), get(port, '/slots')
49
+ return bool(isinstance(props, dict) and Path(props.get('model_path', '')).resolve() == weight
50
+ and isinstance(slots, list) and slots and all(
51
+ isinstance(slot, dict) and slot.get('is_processing') is False
52
+ and type(slot.get('n_ctx')) is int and 0 < slot['n_ctx'] <= 8192
53
+ for slot in slots))
54
+ except (OSError, ValueError, TypeError, IndexError, http.client.HTTPException):
55
+ return False
56
+
57
+
58
+ def external_accelerator_work():
59
+ """Conservative process-name guard; never reads/prints private task payloads."""
60
+ rows = subprocess.check_output(['ps', '-axo', 'pid=,command='], text=True)
61
+ candidates = []
62
+ markers = {'encoder_experiment.py': 'encoder_training',
63
+ 'image_tool.py --': 'image_generation', 'sd-server': 'image_backend',
64
+ 'mlx_vlm server': 'mlx_server', 'mlx_dspark serve': 'mlx_server',
65
+ 'llama-server': 'llama_server'}
66
+ for row in rows.splitlines():
67
+ fields = row.strip().split(None, 1)
68
+ if len(fields) != 2 or int(fields[0]) == os.getpid():
69
+ continue
70
+ command = fields[1]
71
+ # Parent shells can carry the worker command in their -c script; do not
72
+ # mistake our own launch wrapper for an active GPU worker.
73
+ if command.startswith(('/bin/bash ', '/bin/zsh ', '/usr/bin/bash ')):
74
+ continue
75
+ for marker, kind in markers.items():
76
+ if marker in command:
77
+ if kind == 'llama_server' and small_idle_llama(shlex.split(command)):
78
+ break
79
+ candidates.append({'pid': int(fields[0]), 'kind': kind})
80
+ break
81
+ return candidates
82
+
83
+
84
+ def run_window(command, output, *, timeout=900, controller=stack_controller,
85
+ external_work=None):
86
+ output = Path(output)
87
+ output.mkdir(parents=True, exist_ok=True)
88
+ receipt = output / 'window.json'
89
+ if receipt.exists():
90
+ raise ValueError('Window output already exists; preserve previous evidence')
91
+ state = {'owner_pid': os.getpid(), 'started_at': time.time(), 'restored': False,
92
+ 'authorization': 'operator resume after explicit temporary-pause notice',
93
+ 'worker_returncode': None, 'timed_out': False}
94
+ def save():
95
+ receipt.write_text(json.dumps(state, indent=2) + '\n')
96
+ with controller.lock():
97
+ detector = external_work or (external_accelerator_work if controller is stack_controller else lambda: [])
98
+ external = detector()
99
+ state['external_accelerator_jobs'] = external
100
+ if external:
101
+ state['phase'] = 'blocked_before_unload'
102
+ state['restored'] = True # No state was changed; prior service remains.
103
+ save()
104
+ raise RuntimeError('Another accelerator/GPU job is active; no backend unloaded')
105
+ active = [profile for profile in controller.profiles().values() if controller.occupied(profile.port)]
106
+ if len(active) > 1:
107
+ raise RuntimeError('Multiple engines active; refusing ambiguous ownership')
108
+ if controller.occupied(18800) or controller.occupied(18798):
109
+ raise RuntimeError('Lab engine already active')
110
+ previous = active[0] if active else None
111
+ if previous:
112
+ if previous.kind != 'text' or not controller.loaded(controller.label(previous)):
113
+ raise RuntimeError('Current engine ownership is not verified')
114
+ if not controller.text_snapshot_idle(controller.request_json(previous, '/status')):
115
+ raise RuntimeError('Current engine busy or idle snapshot unknown')
116
+ controller.validate_paths(previous)
117
+ state['restore_profile'] = previous.key if previous else None
118
+ save()
119
+ process = None
120
+ paused = False
121
+ try:
122
+ if previous:
123
+ controller.stop_all()
124
+ paused = True
125
+ state['phase'] = 'worker'
126
+ save()
127
+ with (output / 'worker.log').open('wb') as log:
128
+ process = subprocess.Popen(command, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT,
129
+ stdin=subprocess.DEVNULL, start_new_session=True)
130
+ state['worker_pid'] = process.pid
131
+ save()
132
+ try:
133
+ state['worker_returncode'] = process.wait(timeout=timeout)
134
+ except subprocess.TimeoutExpired:
135
+ state['timed_out'] = True
136
+ os.killpg(process.pid, signal.SIGTERM)
137
+ try:
138
+ process.wait(timeout=20)
139
+ except subprocess.TimeoutExpired:
140
+ os.killpg(process.pid, signal.SIGKILL)
141
+ process.wait()
142
+ state['worker_returncode'] = process.returncode
143
+ finally:
144
+ if process is not None and process.poll() is None:
145
+ os.killpg(process.pid, signal.SIGTERM)
146
+ try:
147
+ process.wait(timeout=20)
148
+ except subprocess.TimeoutExpired:
149
+ os.killpg(process.pid, signal.SIGKILL)
150
+ process.wait()
151
+ state['phase'] = 'restoring'
152
+ try:
153
+ save()
154
+ finally:
155
+ if paused:
156
+ controller.start_locked(previous, quiet=True)
157
+ state['restored'] = controller.status(previous)['api_ready']
158
+ else:
159
+ state['restored'] = previous is None
160
+ state['phase'] = 'finished' if state['restored'] else 'restore_failed'
161
+ state['finished_at'] = time.time()
162
+ save()
163
+ if not state['restored']:
164
+ raise RuntimeError('Prior service restoration failed; inspect window receipt')
165
+ return state
166
+
167
+
168
+ if __name__ == '__main__':
169
+ parser = argparse.ArgumentParser()
170
+ parser.add_argument('--output', type=Path, required=True)
171
+ parser.add_argument('--timeout', type=float, default=900)
172
+ parser.add_argument('command', nargs=argparse.REMAINDER)
173
+ args = parser.parse_args()
174
+ command = args.command[1:] if args.command[:1] == ['--'] else args.command
175
+ if not command:
176
+ parser.error('worker command required')
177
+ result = run_window(command, args.output, timeout=args.timeout)
178
+ print(json.dumps(result, indent=2))
179
+ raise SystemExit(0 if result['worker_returncode'] == 0 else 1)
mlx_agent_tools/raw/upstream/language.py ADDED
@@ -0,0 +1,1932 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import lru_cache, partial
2
+ from typing import Any, List, Optional
3
+
4
+ import mlx.core as mx
5
+ import mlx.nn as nn
6
+
7
+ from ...speculative.cache_state import (
8
+ rollback_speculative_cache as rollback_cache_transaction,
9
+ )
10
+ from ..activations import swiglu
11
+ from ..base import (
12
+ LanguageModelOutput,
13
+ create_attention_mask,
14
+ scaled_dot_product_attention,
15
+ )
16
+ from ..cache import ArraysCache, KVCache
17
+ from ..rope_utils import MRoPERotaryEmbedding
18
+ from ..rope_utils import apply_multimodal_rotary_pos_emb as _apply_mrope
19
+ from .config import ModelConfig, TextConfig
20
+ from .gated_delta import gated_delta_update
21
+ from .speculative_verifier import Qwen3_5ExactSpeculativeVerifier
22
+
23
+ _EXACT_SPECULATIVE_VERIFIER = Qwen3_5ExactSpeculativeVerifier()
24
+
25
+
26
+ class Qwen3_5RotaryEmbedding(MRoPERotaryEmbedding):
27
+ def __init__(
28
+ self,
29
+ dim,
30
+ max_position_embeddings=2048,
31
+ base=10000,
32
+ mrope_section=[11, 11, 0],
33
+ ):
34
+ super().__init__(
35
+ dim,
36
+ max_position_embeddings=max_position_embeddings,
37
+ base=base,
38
+ mrope_section=mrope_section,
39
+ style="interleaved",
40
+ )
41
+ mx.eval(self.inv_freq)
42
+
43
+
44
+ def apply_multimodal_rotary_pos_emb(q, k, cos, sin, unqueeze_dim=1):
45
+ return _apply_mrope(q, k, cos, sin, style="interleaved", unsqueeze_dim=unqueeze_dim)
46
+
47
+
48
+ class Qwen3_5RMSNormGated(nn.Module):
49
+ def __init__(self, hidden_size: int, eps: float = 1e-6):
50
+ super().__init__()
51
+ self.eps = eps
52
+ self.weight = mx.ones(hidden_size)
53
+
54
+ def __call__(
55
+ self, hidden_states: mx.array, gate: mx.array | None = None
56
+ ) -> mx.array:
57
+ x = mx.fast.rms_norm(hidden_states, self.weight, self.eps)
58
+ if gate is not None:
59
+ return _precise_swiglu(hidden_states, gate, x)
60
+ return x.astype(hidden_states.dtype)
61
+
62
+
63
+ @partial(mx.compile, shapeless=True)
64
+ def _precise_swiglu(h, gate, x):
65
+ gate = nn.silu(gate.astype(mx.float32))
66
+ x = x.astype(mx.float32)
67
+ return (gate * x).astype(h.dtype)
68
+
69
+
70
+ @partial(mx.compile, shapeless=True)
71
+ def _qwen3_5_decode_depthwise_conv(conv_input: mx.array, weight: mx.array):
72
+ out = mx.sum(conv_input.astype(mx.float32) * weight[None, :, :], axis=1)
73
+ return out.astype(conv_input.dtype)[:, None, :]
74
+
75
+
76
+ def _extract_row_cache(cache_entry, row: int):
77
+ if isinstance(cache_entry, ArraysCache):
78
+ row_cache = ArraysCache(size=len(cache_entry.cache))
79
+ row_cache.cache = [
80
+ None if cached is None else cached[row : row + 1]
81
+ for cached in cache_entry.cache
82
+ ]
83
+ lengths = getattr(cache_entry, "lengths", None)
84
+ if lengths is not None:
85
+ row_cache.lengths = lengths[row : row + 1]
86
+ return row_cache
87
+
88
+ if hasattr(cache_entry, "extract") and not cache_entry.empty():
89
+ return cache_entry.extract(row)
90
+
91
+ if hasattr(cache_entry, "left_padding"):
92
+ row_cache = KVCache()
93
+ return row_cache
94
+
95
+ return cache_entry
96
+
97
+
98
+ def _is_single_row_batch_cache(cache_entry) -> bool:
99
+ left_padding = getattr(cache_entry, "left_padding", None)
100
+ # Quantized batch caches must update in place; the singleton shortcut
101
+ # rebuilds only plain BatchKVCache state after the row-wise forward.
102
+ return (
103
+ isinstance(left_padding, mx.array)
104
+ and left_padding.ndim > 0
105
+ and left_padding.size == 1
106
+ and not hasattr(cache_entry, "bits")
107
+ )
108
+
109
+
110
+ def _pad_row_time(x: mx.array, pad: int, target_length: int) -> mx.array:
111
+ if pad <= 0:
112
+ return x
113
+ if x.shape[1] >= target_length:
114
+ return x
115
+ return mx.concatenate(
116
+ [
117
+ mx.zeros((x.shape[0], pad, *x.shape[2:]), dtype=x.dtype),
118
+ x,
119
+ ],
120
+ axis=1,
121
+ )
122
+
123
+
124
+ def _restore_batch_padding_metadata(cache_entry, offsets, steps: int):
125
+ if offsets is None:
126
+ return cache_entry
127
+ if not (
128
+ hasattr(cache_entry, "offset")
129
+ and hasattr(cache_entry, "left_padding")
130
+ and hasattr(cache_entry, "_idx")
131
+ ):
132
+ return cache_entry
133
+ cache_entry.offset = offsets + steps
134
+ cache_entry.left_padding = cache_entry._idx - cache_entry.offset
135
+ return cache_entry
136
+
137
+
138
+ def _qwen3_5_refresh_metadata(cache):
139
+ revision = getattr(cache, "metadata_revision", 0)
140
+ if getattr(cache, "_qwen3_5_metadata_revision", None) != revision:
141
+ for name in (
142
+ "_qwen3_5_lengths_info",
143
+ "_qwen3_5_ssm_no_mask_batch_size",
144
+ ):
145
+ if hasattr(cache, name):
146
+ delattr(cache, name)
147
+ cache._qwen3_5_metadata_revision = revision
148
+
149
+
150
+ def _qwen3_5_left_padding_info(cache):
151
+ if cache is not None:
152
+ _qwen3_5_refresh_metadata(cache)
153
+ left_padding = getattr(cache, "left_padding", None)
154
+ if not (
155
+ isinstance(left_padding, mx.array)
156
+ and left_padding.ndim > 0
157
+ and left_padding.size > 0
158
+ ):
159
+ return None
160
+
161
+ # Padding arrays can change in place without changing their identity.
162
+ pads = tuple(int(p) for p in left_padding.tolist())
163
+ return pads, max(pads)
164
+
165
+
166
+ def _qwen3_5_lengths_info(cache):
167
+ if cache is not None:
168
+ _qwen3_5_refresh_metadata(cache)
169
+ lengths = getattr(cache, "lengths", None)
170
+ if not (isinstance(lengths, mx.array) and lengths.ndim > 0 and lengths.size > 0):
171
+ return None
172
+ cached = getattr(cache, "_qwen3_5_lengths_info", None)
173
+ if cached is None or cached[0] is not lengths:
174
+ values = tuple(int(v) for v in lengths.tolist())
175
+ cached = (lengths, min(values) if values else 0)
176
+ cache._qwen3_5_lengths_info = cached
177
+ return cached[1]
178
+
179
+
180
+ def _qwen3_5_advance_lengths_info(cache, steps: int):
181
+ lengths = getattr(cache, "lengths", None)
182
+ cached = getattr(cache, "_qwen3_5_lengths_info", None)
183
+ if cached is None or not isinstance(lengths, mx.array):
184
+ return
185
+ _lengths, min_value = cached
186
+ cache._qwen3_5_lengths_info = (lengths, min_value - steps)
187
+
188
+
189
+ def _create_qwen3_5_ssm_mask(h: mx.array, cache):
190
+ if cache is not None:
191
+ _qwen3_5_refresh_metadata(cache)
192
+ if not (cache and hasattr(cache, "make_mask")):
193
+ return None
194
+
195
+ lengths = getattr(cache, "lengths", None)
196
+ left_padding = getattr(cache, "left_padding", None)
197
+ if isinstance(left_padding, mx.array):
198
+ batch_size = int(left_padding.shape[0]) if left_padding.ndim > 0 else 1
199
+ if (
200
+ lengths is None
201
+ and getattr(cache, "_qwen3_5_ssm_no_mask_batch_size", None) == batch_size
202
+ ):
203
+ return None
204
+ left_padding_info = _qwen3_5_left_padding_info(cache)
205
+ max_left_padding = left_padding_info[1] if left_padding_info else 0
206
+ if max_left_padding <= 0:
207
+ if lengths is None:
208
+ cache._qwen3_5_ssm_no_mask_batch_size = batch_size
209
+ return None
210
+ if hasattr(cache, "_qwen3_5_ssm_no_mask_batch_size"):
211
+ delattr(cache, "_qwen3_5_ssm_no_mask_batch_size")
212
+
213
+ lengths_min = _qwen3_5_lengths_info(cache)
214
+ if lengths_min is not None and lengths_min >= h.shape[1]:
215
+ return None
216
+
217
+ return cache.make_mask(h.shape[1])
218
+
219
+
220
+ def _create_qwen3_5_attention_mask(h: mx.array, cache):
221
+ if cache is None:
222
+ return create_attention_mask(h, cache)
223
+
224
+ if hasattr(cache, "_qwen3_5_decode_left_padding"):
225
+ delattr(cache, "_qwen3_5_decode_left_padding")
226
+
227
+ left_padding = getattr(cache, "left_padding", None)
228
+ if h.shape[1] == 1 and isinstance(left_padding, mx.array) and left_padding.ndim > 0:
229
+ left_padding_info = _qwen3_5_left_padding_info(cache)
230
+ if left_padding_info is None or left_padding_info[1] <= 0:
231
+ return None
232
+ cache._qwen3_5_decode_left_padding = list(left_padding_info[0])
233
+ return "left_padded_decode"
234
+ return create_attention_mask(h, cache)
235
+
236
+
237
+ def _set_qwen3_5_decode_left_padding(caches, layers, pads):
238
+ if caches is None:
239
+ return
240
+ for layer, cache_entry in zip(layers, caches):
241
+ if layer.is_linear or cache_entry is None:
242
+ continue
243
+ if pads is None:
244
+ if hasattr(cache_entry, "_qwen3_5_decode_left_padding"):
245
+ delattr(cache_entry, "_qwen3_5_decode_left_padding")
246
+ else:
247
+ cache_entry._qwen3_5_decode_left_padding = pads
248
+
249
+
250
+ _QWEN3_5_RAGGED_SDPA_ONE_PASS_SOURCE = r"""
251
+ uint q_batch_head_idx = threadgroup_position_in_grid.y;
252
+ uint simd_gid = simdgroup_index_in_threadgroup;
253
+ uint simd_lid = thread_index_in_simdgroup;
254
+
255
+ constexpr int BN = 32;
256
+ constexpr int BD = 32;
257
+ constexpr int qk_per_thread = D_SIZE / BD;
258
+ constexpr int v_per_thread = V_SIZE / BD;
259
+
260
+ typedef float U;
261
+ thread U q[qk_per_thread];
262
+ thread U k[qk_per_thread];
263
+ thread U o[v_per_thread];
264
+ threadgroup U outputs[BN * BD];
265
+ threadgroup U max_scores[BN];
266
+ threadgroup U sum_exp_scores[BN];
267
+
268
+ int K_SIZE = int(k_size[0]);
269
+ int batch_idx = int(q_batch_head_idx) / NUM_Q_HEADS;
270
+ int q_head_idx = int(q_batch_head_idx) - batch_idx * NUM_Q_HEADS;
271
+ int kv_head_idx = q_head_idx / GQA_FACTOR;
272
+ int pad = int(pads[batch_idx]);
273
+ int N = K_SIZE - pad;
274
+
275
+ const device T* qptr =
276
+ queries + int(q_batch_head_idx) * D_SIZE + int(simd_lid) * qk_per_thread;
277
+ const device T* kptr =
278
+ keys + (batch_idx * NUM_KV_HEADS + kv_head_idx) * K_SIZE * D_SIZE +
279
+ (pad + int(simd_gid)) * D_SIZE + int(simd_lid) * qk_per_thread;
280
+ const device T* vptr =
281
+ values + (batch_idx * NUM_KV_HEADS + kv_head_idx) * K_SIZE * V_SIZE +
282
+ (pad + int(simd_gid)) * V_SIZE + int(simd_lid) * v_per_thread;
283
+ device T* optr =
284
+ out + int(q_batch_head_idx) * V_SIZE + int(simd_gid) * v_per_thread;
285
+
286
+ U s = U(scale[0]);
287
+ for (int i = 0; i < qk_per_thread; i++) {
288
+ q[i] = s * qptr[i];
289
+ }
290
+ for (int i = 0; i < v_per_thread; i++) {
291
+ o[i] = 0;
292
+ }
293
+
294
+ U max_score = -3.4028234663852886e38f;
295
+ U sum_exp_score = 0;
296
+
297
+ for (int i = int(simd_gid); i < N; i += BN) {
298
+ for (int j = 0; j < qk_per_thread; j++) {
299
+ k[j] = kptr[j];
300
+ }
301
+
302
+ U score = 0;
303
+ for (int j = 0; j < qk_per_thread; j++) {
304
+ score += q[j] * k[j];
305
+ }
306
+ score = simd_sum(score);
307
+
308
+ U new_max = max(max_score, score);
309
+ U factor = fast::exp(max_score - new_max);
310
+ U exp_score = fast::exp(score - new_max);
311
+
312
+ max_score = new_max;
313
+ sum_exp_score = sum_exp_score * factor + exp_score;
314
+
315
+ for (int j = 0; j < v_per_thread; j++) {
316
+ o[j] = o[j] * factor + exp_score * vptr[j];
317
+ }
318
+
319
+ kptr += BN * D_SIZE;
320
+ vptr += BN * V_SIZE;
321
+ }
322
+
323
+ if (simd_lid == 0) {
324
+ max_scores[simd_gid] = max_score;
325
+ sum_exp_scores[simd_gid] = sum_exp_score;
326
+ }
327
+ threadgroup_barrier(mem_flags::mem_threadgroup);
328
+
329
+ max_score = max_scores[simd_lid];
330
+ U new_max = simd_max(max_score);
331
+ U factor = fast::exp(max_score - new_max);
332
+ sum_exp_score = simd_sum(sum_exp_scores[simd_lid] * factor);
333
+
334
+ for (int i = 0; i < v_per_thread; i++) {
335
+ outputs[simd_lid * BD + simd_gid] = o[i];
336
+ threadgroup_barrier(mem_flags::mem_threadgroup);
337
+ o[i] = simd_sum(outputs[simd_gid * BD + simd_lid] * factor);
338
+ o[i] = sum_exp_score == 0 ? o[i] : (o[i] / sum_exp_score);
339
+ threadgroup_barrier(mem_flags::mem_threadgroup);
340
+ }
341
+
342
+ if (simd_lid == 0) {
343
+ for (int i = 0; i < v_per_thread; i++) {
344
+ optr[i] = static_cast<T>(o[i]);
345
+ }
346
+ }
347
+ """
348
+
349
+
350
+ _QWEN3_5_RAGGED_SDPA_TWO_PASS_1_SOURCE = r"""
351
+ uint simd_lid = thread_index_in_simdgroup;
352
+ uint kv_head_idx = threadgroup_position_in_grid.x;
353
+ uint batch_idx = threadgroup_position_in_grid.y;
354
+ uint block_idx = threadgroup_position_in_grid.z;
355
+ uint gqa_idx = thread_position_in_threadgroup.y;
356
+
357
+ constexpr int BD = 32;
358
+ constexpr int qk_per_thread = D_SIZE / BD;
359
+ constexpr int v_per_thread = V_SIZE / BD;
360
+
361
+ typedef float U;
362
+ thread U q[qk_per_thread];
363
+ thread U o[v_per_thread] = {0};
364
+
365
+ int K_SIZE = int(k_size[0]);
366
+ int q_head_idx = int(GQA_FACTOR * kv_head_idx + gqa_idx);
367
+ int q_batch_head_idx = int(batch_idx) * NUM_Q_HEADS + q_head_idx;
368
+ int pad = int(pads[batch_idx]);
369
+ int N = K_SIZE - pad;
370
+
371
+ const device T* qptr =
372
+ queries + q_batch_head_idx * D_SIZE + int(simd_lid) * qk_per_thread;
373
+ const device T* kptr =
374
+ keys + (int(batch_idx) * NUM_KV_HEADS + int(kv_head_idx)) *
375
+ K_SIZE * D_SIZE +
376
+ (pad + int(block_idx)) * D_SIZE + int(simd_lid) * qk_per_thread;
377
+ const device T* vptr =
378
+ values + (int(batch_idx) * NUM_KV_HEADS + int(kv_head_idx)) *
379
+ K_SIZE * V_SIZE +
380
+ (pad + int(block_idx)) * V_SIZE + int(simd_lid) * v_per_thread;
381
+ device T* optr =
382
+ partials + q_batch_head_idx * BLOCKS * V_SIZE +
383
+ int(block_idx) * V_SIZE + int(simd_lid) * v_per_thread;
384
+ device float* sump =
385
+ sums + q_batch_head_idx * BLOCKS + int(block_idx);
386
+ device float* maxp =
387
+ maxs + q_batch_head_idx * BLOCKS + int(block_idx);
388
+
389
+ U s = U(scale[0]);
390
+ for (int i = 0; i < qk_per_thread; i++) {
391
+ q[i] = s * qptr[i];
392
+ }
393
+
394
+ U max_score = -3.4028234663852886e38f;
395
+ U sum_exp_score = 0;
396
+
397
+ for (int i = int(block_idx); i < N; i += BLOCKS) {
398
+ U score = 0;
399
+ for (int j = 0; j < qk_per_thread; j++) {
400
+ score += q[j] * kptr[j];
401
+ }
402
+ score = simd_sum(score);
403
+
404
+ U new_max = max(max_score, score);
405
+ U factor = fast::exp(max_score - new_max);
406
+ U exp_score = fast::exp(score - new_max);
407
+
408
+ max_score = new_max;
409
+ sum_exp_score = sum_exp_score * factor + exp_score;
410
+
411
+ for (int j = 0; j < v_per_thread; j++) {
412
+ o[j] = o[j] * factor + exp_score * vptr[j];
413
+ }
414
+
415
+ kptr += BLOCKS * D_SIZE;
416
+ vptr += BLOCKS * V_SIZE;
417
+ }
418
+
419
+ if (simd_lid == 0) {
420
+ sump[0] = sum_exp_score;
421
+ maxp[0] = max_score;
422
+ }
423
+ for (int i = 0; i < v_per_thread; i++) {
424
+ optr[i] = static_cast<T>(o[i]);
425
+ }
426
+ """
427
+
428
+
429
+ _QWEN3_5_RAGGED_SDPA_TWO_PASS_2_SOURCE = r"""
430
+ uint q_batch_head_idx = threadgroup_position_in_grid.y;
431
+ uint simd_gid = simdgroup_index_in_threadgroup;
432
+ uint simd_lid = thread_index_in_simdgroup;
433
+
434
+ constexpr int BN = 32;
435
+ constexpr int BD = 32;
436
+ constexpr int elem_per_thread = D_SIZE / BD;
437
+
438
+ typedef float U;
439
+ thread U o[elem_per_thread] = {0};
440
+ threadgroup U outputs[BN * BD];
441
+
442
+ const device T* part =
443
+ partials + int(q_batch_head_idx) * BLOCKS * D_SIZE +
444
+ int(simd_gid) * D_SIZE + int(simd_lid) * elem_per_thread;
445
+ const device float* sump = sums + int(q_batch_head_idx) * BLOCKS;
446
+ const device float* maxp = maxs + int(q_batch_head_idx) * BLOCKS;
447
+ device T* optr =
448
+ out + int(q_batch_head_idx) * D_SIZE + int(simd_gid) * elem_per_thread;
449
+
450
+ U sum_exp_score = 0.0;
451
+ U max_score = -3.4028234663852886e38f;
452
+
453
+ for (int b = 0; b < BLOCKS / BN; ++b) {
454
+ max_score = max(max_score, maxp[int(simd_lid) + BN * b]);
455
+ }
456
+ max_score = simd_max(max_score);
457
+
458
+ for (int b = 0; b < BLOCKS / BN; ++b) {
459
+ U factor = fast::exp(maxp[int(simd_lid) + BN * b] - max_score);
460
+ sum_exp_score += factor * sump[int(simd_lid) + BN * b];
461
+ }
462
+ sum_exp_score = simd_sum(sum_exp_score);
463
+
464
+ for (int b = 0; b < BLOCKS / BN; ++b) {
465
+ U factor = fast::exp(maxp[int(simd_gid)] - max_score);
466
+ for (int i = 0; i < elem_per_thread; i++) {
467
+ o[i] += factor * static_cast<U>(part[i]);
468
+ }
469
+ maxp += BN;
470
+ sump += BN;
471
+ part += BN * D_SIZE;
472
+ }
473
+
474
+ for (int i = 0; i < elem_per_thread; i++) {
475
+ outputs[simd_lid * BD + simd_gid] = o[i];
476
+ threadgroup_barrier(mem_flags::mem_threadgroup);
477
+ o[i] = simd_sum(outputs[simd_gid * BD + simd_lid]);
478
+ o[i] = sum_exp_score == 0 ? o[i] : (o[i] / sum_exp_score);
479
+ threadgroup_barrier(mem_flags::mem_threadgroup);
480
+ }
481
+
482
+ if (simd_lid == 0) {
483
+ for (int i = 0; i < elem_per_thread; i++) {
484
+ optr[i] = static_cast<T>(o[i]);
485
+ }
486
+ }
487
+ """
488
+
489
+
490
+ @lru_cache(maxsize=1)
491
+ def _qwen3_5_device_arch_suffix() -> str:
492
+ info = mx.device_info() if hasattr(mx, "device_info") else mx.metal.device_info()
493
+ return str(info.get("architecture", ""))[-1:]
494
+
495
+
496
+ def _qwen3_5_sdpa_vector_blocks(seq_len: int, gqa_factor: int) -> int:
497
+ devc = _qwen3_5_device_arch_suffix()
498
+ n_simds = gqa_factor
499
+ if devc == "s":
500
+ blocks = 64
501
+ if seq_len > 1024 and n_simds > 4:
502
+ if seq_len <= 8192:
503
+ blocks = 128
504
+ elif seq_len <= 32768:
505
+ blocks = 256
506
+ elif seq_len <= 65536:
507
+ blocks = 512
508
+ else:
509
+ blocks = 1024
510
+ return blocks
511
+ if devc == "d":
512
+ blocks = 128
513
+ if n_simds <= 2 and seq_len > 8192:
514
+ blocks = 256
515
+ elif n_simds >= 6:
516
+ if 16384 <= seq_len < 65536:
517
+ blocks = 512
518
+ elif seq_len >= 65536:
519
+ blocks = 1024
520
+ return blocks
521
+ if n_simds >= 4:
522
+ return 64
523
+ return 32
524
+
525
+
526
+ def _qwen3_5_sdpa_vector_plan(seq_len: int, q_heads: int, kv_heads: int):
527
+ devc = _qwen3_5_device_arch_suffix()
528
+ if (devc in {"d", "s"} and seq_len >= 1024) or (
529
+ kv_heads < q_heads and seq_len >= 4096
530
+ ):
531
+ return ("two_pass", _qwen3_5_sdpa_vector_blocks(seq_len, q_heads // kv_heads))
532
+ return ("one_pass", 0)
533
+
534
+
535
+ @lru_cache(maxsize=None)
536
+ def _qwen3_5_ragged_sdpa_one_pass_kernel(dtype, d_size, v_size):
537
+ dtype_name = {mx.bfloat16: "bf16", mx.float16: "fp16"}.get(dtype, "unk")
538
+ return mx.fast.metal_kernel(
539
+ name=f"qwen3_5_ragged_sdpa_1p_{dtype_name}_d{d_size}_v{v_size}",
540
+ input_names=["queries", "keys", "values", "pads", "scale", "k_size"],
541
+ output_names=["out"],
542
+ header="#include <metal_simdgroup>\nusing namespace metal;\n",
543
+ source=_QWEN3_5_RAGGED_SDPA_ONE_PASS_SOURCE,
544
+ )
545
+
546
+
547
+ @lru_cache(maxsize=None)
548
+ def _qwen3_5_ragged_sdpa_two_pass_1_kernel(dtype, d_size, v_size, blocks):
549
+ dtype_name = {mx.bfloat16: "bf16", mx.float16: "fp16"}.get(dtype, "unk")
550
+ return mx.fast.metal_kernel(
551
+ name=(
552
+ f"qwen3_5_ragged_sdpa_2p1_{dtype_name}_" f"d{d_size}_v{v_size}_b{blocks}"
553
+ ),
554
+ input_names=["queries", "keys", "values", "pads", "scale", "k_size"],
555
+ output_names=["partials", "sums", "maxs"],
556
+ header="#include <metal_simdgroup>\nusing namespace metal;\n",
557
+ source=_QWEN3_5_RAGGED_SDPA_TWO_PASS_1_SOURCE,
558
+ )
559
+
560
+
561
+ @lru_cache(maxsize=None)
562
+ def _qwen3_5_ragged_sdpa_two_pass_2_kernel(dtype, v_size, blocks):
563
+ dtype_name = {mx.bfloat16: "bf16", mx.float16: "fp16"}.get(dtype, "unk")
564
+ return mx.fast.metal_kernel(
565
+ name=f"qwen3_5_ragged_sdpa_2p2_{dtype_name}_v{v_size}_b{blocks}",
566
+ input_names=["partials", "sums", "maxs"],
567
+ output_names=["out"],
568
+ header="#include <metal_simdgroup>\nusing namespace metal;\n",
569
+ source=_QWEN3_5_RAGGED_SDPA_TWO_PASS_2_SOURCE,
570
+ )
571
+
572
+
573
+ @lru_cache(maxsize=128)
574
+ def _qwen3_5_cached_i32_array(values):
575
+ return mx.array(values, dtype=mx.int32)
576
+
577
+
578
+ @lru_cache(maxsize=128)
579
+ def _qwen3_5_cached_sdpa_scalars(scale: float, k_size: int):
580
+ return (
581
+ mx.array([scale], dtype=mx.float32),
582
+ mx.array([k_size], dtype=mx.int32),
583
+ )
584
+
585
+
586
+ # Threads per threadgroup the one-pass kernel and the second pass of the
587
+ # two-pass plan are written for. Both assume exactly 32 SIMD groups of 32 lanes
588
+ # (BN == BD == 32): the block reduction and the threadgroup transpose index off
589
+ # simd_gid over [0, 32), so this cannot simply be lowered without reworking them.
590
+ _QWEN3_5_SDPA_THREADS = 1024
591
+
592
+ # Metal caps threads-per-threadgroup per compiled *pipeline*, not per device --
593
+ # a kernel holding more registers live gets a lower ceiling than the device
594
+ # maximum. At D_SIZE == 256 the two-pass reduction keeps elem_per_thread == 8
595
+ # floats per thread, and on applegpu_g14d (M2 Ultra) that compiles to a ceiling
596
+ # of 896 threads, so requesting 1024 raises:
597
+ #
598
+ # ValueError: Thread group size (1024) is greater than the maximum allowed
599
+ # threads per threadgroup (896).
600
+ #
601
+ # D_SIZE is what moves it: 64/96/128 launch fine on the same GPU, and the same
602
+ # 256 launches fine on applegpu_g16s (M4 Max). Nothing in the shapes predicts
603
+ # which parts are affected, and the error is raised lazily
604
+ # when the command buffer is built rather than when the kernel is called, so it
605
+ # cannot be caught around the call site. Probe each kernel signature once with a
606
+ # forced eval, cache the verdict, and route around whichever launches this GPU
607
+ # rejects: two-pass degrades to one-pass, one-pass degrades to the caller's
608
+ # portable per-pad-group fallback. No-op wherever 1024 threads are legal.
609
+ _QWEN3_5_SDPA_LAUNCHABLE = {}
610
+
611
+
612
+ def _qwen3_5_try_launch(key, launch):
613
+ """Run ``launch()``, or return None if this GPU rejects that launch.
614
+
615
+ ``key`` must capture everything that determines the compiled pipeline (the
616
+ kernel and its template arguments), so the verdict is cached per pipeline
617
+ rather than per call.
618
+ """
619
+ verdict = _QWEN3_5_SDPA_LAUNCHABLE.get(key)
620
+ if verdict is False:
621
+ return None
622
+ try:
623
+ outputs = launch()
624
+ if verdict is None:
625
+ # First use of this pipeline: force it now so an illegal
626
+ # threadgroup surfaces here instead of at the caller's next eval.
627
+ mx.eval(outputs)
628
+ _QWEN3_5_SDPA_LAUNCHABLE[key] = True
629
+ return outputs
630
+ except ValueError:
631
+ _QWEN3_5_SDPA_LAUNCHABLE[key] = False
632
+ return None
633
+
634
+
635
+ def _qwen3_5_ragged_decode_attention(
636
+ queries: mx.array,
637
+ keys: mx.array,
638
+ values: mx.array,
639
+ pads: List[int],
640
+ scale: float,
641
+ ) -> Optional[mx.array]:
642
+ # Metal-only fast path; on other backends (e.g. CUDA) return None so the
643
+ # caller falls back to portable per-pad-group scaled_dot_product_attention.
644
+ if not mx.metal.is_available():
645
+ return None
646
+ if (
647
+ queries.ndim != 4
648
+ or keys.ndim != 4
649
+ or values.ndim != 4
650
+ or queries.shape[2] != 1
651
+ or queries.dtype not in (mx.bfloat16, mx.float16)
652
+ or keys.dtype != queries.dtype
653
+ or values.dtype != queries.dtype
654
+ ):
655
+ return None
656
+
657
+ batch, q_heads, _, d_size = queries.shape
658
+ pads = tuple(int(p) for p in pads)
659
+ if len(pads) != batch or any(p < 0 for p in pads):
660
+ return None
661
+ kv_heads = keys.shape[1]
662
+ k_size = keys.shape[2]
663
+ v_size = values.shape[-1]
664
+ if (
665
+ q_heads % kv_heads != 0
666
+ or d_size != v_size
667
+ or d_size not in (64, 96, 128, 256)
668
+ or any(p >= k_size for p in pads)
669
+ ):
670
+ return None
671
+
672
+ plans = [_qwen3_5_sdpa_vector_plan(k_size - pad, q_heads, kv_heads) for pad in pads]
673
+ if len(set(plans)) != 1:
674
+ return None
675
+ mode, blocks = plans[0]
676
+
677
+ queries = mx.contiguous(queries)
678
+ keys = mx.contiguous(keys)
679
+ values = mx.contiguous(values)
680
+ pads_array = _qwen3_5_cached_i32_array(pads)
681
+ scale_array, k_size_array = _qwen3_5_cached_sdpa_scalars(float(scale), int(k_size))
682
+ template = [
683
+ ("T", queries.dtype),
684
+ ("D_SIZE", int(d_size)),
685
+ ("V_SIZE", int(v_size)),
686
+ ("NUM_Q_HEADS", int(q_heads)),
687
+ ("NUM_KV_HEADS", int(kv_heads)),
688
+ ("GQA_FACTOR", int(q_heads // kv_heads)),
689
+ ]
690
+
691
+ signature = (queries.dtype, int(d_size), int(v_size), int(q_heads), int(kv_heads))
692
+
693
+ if mode == "two_pass":
694
+ kernel_1 = _qwen3_5_ragged_sdpa_two_pass_1_kernel(
695
+ queries.dtype, d_size, v_size, blocks
696
+ )
697
+ pass_1 = _qwen3_5_try_launch(
698
+ ("two_pass_1", *signature, int(blocks)),
699
+ lambda: kernel_1(
700
+ inputs=[queries, keys, values, pads_array, scale_array, k_size_array],
701
+ template=[*template, ("BLOCKS", int(blocks))],
702
+ grid=(32 * kv_heads, (q_heads // kv_heads) * batch, blocks),
703
+ threadgroup=(32, q_heads // kv_heads, 1),
704
+ output_shapes=[
705
+ (batch, q_heads, 1, blocks, v_size),
706
+ (batch, q_heads, 1, blocks),
707
+ (batch, q_heads, 1, blocks),
708
+ ],
709
+ output_dtypes=[queries.dtype, mx.float32, mx.float32],
710
+ ),
711
+ )
712
+ if pass_1 is not None:
713
+ partials, sums, maxs = pass_1
714
+ kernel_2 = _qwen3_5_ragged_sdpa_two_pass_2_kernel(
715
+ queries.dtype, v_size, blocks
716
+ )
717
+ pass_2 = _qwen3_5_try_launch(
718
+ ("two_pass_2", queries.dtype, int(v_size), int(blocks)),
719
+ lambda: kernel_2(
720
+ inputs=[partials, sums, maxs],
721
+ template=[
722
+ ("T", queries.dtype),
723
+ ("D_SIZE", int(v_size)),
724
+ ("BLOCKS", int(blocks)),
725
+ ],
726
+ grid=(_QWEN3_5_SDPA_THREADS, batch * q_heads, 1),
727
+ threadgroup=(_QWEN3_5_SDPA_THREADS, 1, 1),
728
+ output_shapes=[(batch, q_heads, 1, v_size)],
729
+ output_dtypes=[queries.dtype],
730
+ ),
731
+ )
732
+ if pass_2 is not None:
733
+ return pass_2[0]
734
+ # This GPU will not launch the two-pass kernels at this size. The
735
+ # one-pass kernel computes the same attention in a single dispatch, so
736
+ # prefer it over dropping out of the fast path entirely.
737
+
738
+ kernel = _qwen3_5_ragged_sdpa_one_pass_kernel(queries.dtype, d_size, v_size)
739
+ one_pass = _qwen3_5_try_launch(
740
+ ("one_pass", *signature),
741
+ lambda: kernel(
742
+ inputs=[queries, keys, values, pads_array, scale_array, k_size_array],
743
+ template=template,
744
+ grid=(_QWEN3_5_SDPA_THREADS, batch * q_heads, 1),
745
+ threadgroup=(_QWEN3_5_SDPA_THREADS, 1, 1),
746
+ output_shapes=[(batch, q_heads, 1, v_size)],
747
+ output_dtypes=[queries.dtype],
748
+ ),
749
+ )
750
+ return None if one_pass is None else one_pass[0]
751
+
752
+
753
+ def _qwen3_5_left_padded_attention(
754
+ queries: mx.array,
755
+ keys: mx.array,
756
+ values: mx.array,
757
+ *,
758
+ cache,
759
+ scale: float,
760
+ mask: Optional[mx.array],
761
+ ) -> Optional[mx.array]:
762
+ if hasattr(cache, "bits") or queries.ndim != 4 or keys.ndim != 4:
763
+ return None
764
+
765
+ pads = getattr(cache, "_qwen3_5_decode_left_padding", None)
766
+ if pads is None:
767
+ left_padding_info = _qwen3_5_left_padding_info(cache)
768
+ if left_padding_info is None or left_padding_info[1] <= 0:
769
+ return None
770
+ pads = list(left_padding_info[0])
771
+ if max(pads) <= 0:
772
+ return None
773
+
774
+ output = _qwen3_5_ragged_decode_attention(queries, keys, values, pads, scale)
775
+ if output is not None:
776
+ return output
777
+
778
+ row_outputs = {}
779
+ for pad in sorted(set(pads)):
780
+ rows = [i for i, row_pad in enumerate(pads) if row_pad == pad]
781
+ row_idx = mx.array(rows, dtype=mx.int32)
782
+ group_queries = mx.take(queries, row_idx, axis=0)
783
+ group_keys = mx.take(keys, row_idx, axis=0)[:, :, pad:, :]
784
+ group_values = mx.take(values, row_idx, axis=0)[:, :, pad:, :]
785
+
786
+ if group_queries.shape[2] > 1:
787
+ prefix_len = group_keys.shape[-2] - group_queries.shape[2]
788
+ group_output = mx.concatenate(
789
+ [
790
+ scaled_dot_product_attention(
791
+ group_queries[:, :, i : i + 1, :],
792
+ group_keys[:, :, : prefix_len + i + 1, :],
793
+ group_values[:, :, : prefix_len + i + 1, :],
794
+ cache=None,
795
+ scale=scale,
796
+ mask=None,
797
+ )
798
+ for i in range(group_queries.shape[2])
799
+ ],
800
+ axis=2,
801
+ )
802
+ else:
803
+ group_output = scaled_dot_product_attention(
804
+ group_queries,
805
+ group_keys,
806
+ group_values,
807
+ cache=None,
808
+ scale=scale,
809
+ mask=None,
810
+ )
811
+
812
+ for j, row in enumerate(rows):
813
+ row_outputs[row] = group_output[j : j + 1]
814
+
815
+ return mx.concatenate([row_outputs[i] for i in range(queries.shape[0])], axis=0)
816
+
817
+
818
+ class Qwen3_5Attention(nn.Module):
819
+ def __init__(self, args: TextConfig):
820
+ super().__init__()
821
+ self.num_key_value_heads = args.num_key_value_heads
822
+ self.num_attention_heads = args.num_attention_heads
823
+ self.head_dim = args.head_dim
824
+ self.scale = self.head_dim**-0.5
825
+
826
+ self.q_proj = nn.Linear(
827
+ args.hidden_size,
828
+ self.num_attention_heads * self.head_dim * 2,
829
+ bias=args.attention_bias,
830
+ )
831
+ self.k_proj = nn.Linear(
832
+ args.hidden_size,
833
+ self.num_key_value_heads * self.head_dim,
834
+ bias=args.attention_bias,
835
+ )
836
+ self.v_proj = nn.Linear(
837
+ args.hidden_size,
838
+ self.num_key_value_heads * self.head_dim,
839
+ bias=args.attention_bias,
840
+ )
841
+ self.o_proj = nn.Linear(
842
+ self.num_attention_heads * self.head_dim,
843
+ args.hidden_size,
844
+ bias=args.attention_bias,
845
+ )
846
+
847
+ self.q_norm = nn.RMSNorm(self.head_dim, eps=args.rms_norm_eps)
848
+ self.k_norm = nn.RMSNorm(self.head_dim, eps=args.rms_norm_eps)
849
+
850
+ self.rotary_emb = Qwen3_5RotaryEmbedding(
851
+ int(self.head_dim * args.rope_parameters["partial_rotary_factor"]),
852
+ max_position_embeddings=args.max_position_embeddings,
853
+ base=args.rope_parameters["rope_theta"],
854
+ mrope_section=args.rope_parameters["mrope_section"],
855
+ )
856
+
857
+ def __call__(
858
+ self,
859
+ x: mx.array,
860
+ mask: Optional[mx.array] = None,
861
+ cache: Optional[Any] = None,
862
+ position_ids: Optional[mx.array] = None,
863
+ position_embeddings: Optional[tuple[mx.array, mx.array]] = None,
864
+ ) -> mx.array:
865
+ B, L, D = x.shape
866
+ q_proj_output, keys, values = (
867
+ self.q_proj(x),
868
+ self.k_proj(x),
869
+ self.v_proj(x),
870
+ )
871
+ queries, keys, values, gate, mask = self._prepare_projected_qkv(
872
+ q_proj_output,
873
+ keys,
874
+ values,
875
+ cache,
876
+ position_ids,
877
+ position_embeddings,
878
+ mask,
879
+ )
880
+
881
+ left_padded_decode = (
882
+ mask == "left_padded_decode" if isinstance(mask, str) else False
883
+ )
884
+ if left_padded_decode:
885
+ mask = None
886
+ output = _qwen3_5_left_padded_attention(
887
+ queries, keys, values, cache=cache, scale=self.scale, mask=mask
888
+ )
889
+ else:
890
+ output = None
891
+
892
+ if output is None:
893
+ output = scaled_dot_product_attention(
894
+ queries, keys, values, cache=cache, scale=self.scale, mask=mask
895
+ )
896
+ output = output.transpose(0, 2, 1, 3).reshape(B, L, -1)
897
+
898
+ return self.o_proj(output * mx.sigmoid(gate))
899
+
900
+ def _prepare_projected_qkv(
901
+ self,
902
+ q_proj_output,
903
+ keys,
904
+ values,
905
+ cache,
906
+ position_ids,
907
+ position_embeddings,
908
+ mask,
909
+ ):
910
+ B, L, _ = q_proj_output.shape
911
+ queries, gate = mx.split(
912
+ q_proj_output.reshape(B, L, self.num_attention_heads, -1), 2, axis=-1
913
+ )
914
+ gate = gate.reshape(B, L, -1)
915
+
916
+ queries = self.q_norm(queries).transpose(0, 2, 1, 3)
917
+ keys = self.k_norm(keys.reshape(B, L, self.num_key_value_heads, -1)).transpose(
918
+ 0, 2, 1, 3
919
+ )
920
+ values = values.reshape(B, L, self.num_key_value_heads, -1).transpose(
921
+ 0, 2, 1, 3
922
+ )
923
+
924
+ kv_seq_len = keys.shape[-2]
925
+
926
+ if position_ids is None:
927
+ cache_offset = cache.offset
928
+ if isinstance(cache_offset, mx.array) and cache_offset.ndim > 0:
929
+ offsets = mx.maximum(cache_offset[:B], 0)
930
+ kv_seq_len = kv_seq_len + offsets + 1
931
+ position_ids = offsets[:, None] + mx.arange(L)[None, :]
932
+ position_ids = mx.expand_dims(position_ids, axis=0)
933
+ position_ids = mx.tile(position_ids, (3, 1, 1))
934
+ else:
935
+ if isinstance(cache_offset, mx.array):
936
+ cache_offset = int(cache_offset.item())
937
+ kv_seq_len += cache_offset + 1
938
+ position_ids = mx.arange(cache_offset, cache_offset + L)
939
+ position_ids = mx.expand_dims(position_ids, axis=0)
940
+ position_ids = mx.tile(position_ids, (3, 1, 1))
941
+ else:
942
+ kv_seq_len += cache.offset + 1 if cache is not None else 0
943
+
944
+ if position_embeddings is None:
945
+ queries, keys = self.rotary_emb.apply_rotary(
946
+ queries,
947
+ keys,
948
+ position_ids,
949
+ unsqueeze_dim=1,
950
+ )
951
+ else:
952
+ cos, sin = position_embeddings
953
+ queries, keys = apply_multimodal_rotary_pos_emb(queries, keys, cos, sin)
954
+
955
+ if mask is not None and isinstance(mask, mx.array):
956
+ if (
957
+ cache is not None
958
+ and hasattr(cache, "_idx")
959
+ and hasattr(cache, "left_padding")
960
+ ):
961
+ kv_seq_len = int(cache._idx) + L
962
+ elif isinstance(kv_seq_len, mx.array):
963
+ kv_seq_len = kv_seq_len.max().item()
964
+ mask = mask[..., : int(kv_seq_len)]
965
+
966
+ if cache is not None:
967
+ keys, values = cache.update_and_fetch(keys, values)
968
+ return queries, keys, values, gate, mask
969
+
970
+
971
+ class Qwen3_5MLP(nn.Module):
972
+ def __init__(self, dim, hidden_dim):
973
+ super().__init__()
974
+ self.gate_proj = nn.Linear(dim, hidden_dim, bias=False)
975
+ self.down_proj = nn.Linear(hidden_dim, dim, bias=False)
976
+ self.up_proj = nn.Linear(dim, hidden_dim, bias=False)
977
+
978
+ def __call__(self, x) -> mx.array:
979
+ return self.down_proj(swiglu(self.gate_proj(x), self.up_proj(x)))
980
+
981
+
982
+ class Qwen3_5GatedDeltaNet(nn.Module):
983
+ def __init__(self, config: TextConfig):
984
+ super().__init__()
985
+ self.hidden_size = config.hidden_size
986
+ self.num_v_heads = config.linear_num_value_heads
987
+ self.num_k_heads = config.linear_num_key_heads
988
+ self.head_k_dim = config.linear_key_head_dim
989
+ self.head_v_dim = config.linear_value_head_dim
990
+ self.key_dim = self.head_k_dim * self.num_k_heads
991
+ self.value_dim = self.head_v_dim * self.num_v_heads
992
+ if self.num_v_heads % self.num_k_heads != 0:
993
+ raise ValueError(
994
+ f"num_v_heads ({self.num_v_heads}) must be divisible by num_k_heads ({self.num_k_heads})"
995
+ )
996
+
997
+ self.conv_kernel_size = config.linear_conv_kernel_dim
998
+ self.layer_norm_epsilon = config.rms_norm_eps
999
+
1000
+ self.conv_dim = self.key_dim * 2 + self.value_dim
1001
+ self.conv1d = nn.Conv1d(
1002
+ in_channels=self.conv_dim,
1003
+ out_channels=self.conv_dim,
1004
+ bias=False,
1005
+ kernel_size=self.conv_kernel_size,
1006
+ groups=self.conv_dim,
1007
+ padding=0,
1008
+ )
1009
+
1010
+ self.in_proj_qkv = nn.Linear(
1011
+ self.hidden_size, self.key_dim * 2 + self.value_dim, bias=False
1012
+ )
1013
+ self.in_proj_z = nn.Linear(self.hidden_size, self.value_dim, bias=False)
1014
+ self.in_proj_b = nn.Linear(self.hidden_size, self.num_v_heads, bias=False)
1015
+ self.in_proj_a = nn.Linear(self.hidden_size, self.num_v_heads, bias=False)
1016
+
1017
+ self.dt_bias = mx.ones(self.num_v_heads)
1018
+
1019
+ A = mx.random.uniform(low=0, high=16, shape=(self.num_v_heads,))
1020
+ self.A_log = mx.log(A)
1021
+
1022
+ self.norm = Qwen3_5RMSNormGated(self.head_v_dim, eps=self.layer_norm_epsilon)
1023
+
1024
+ self.out_proj = nn.Linear(self.value_dim, self.hidden_size, bias=False)
1025
+
1026
+ def _causal_conv1d_decode(self, conv_input: mx.array) -> mx.array:
1027
+ cached = getattr(self, "_qwen3_5_decode_conv_weight", None)
1028
+ cache_key = id(self.conv1d.weight)
1029
+ if cached is None or cached[0] != cache_key:
1030
+ weight = self.conv1d.weight[:, :, 0].T.astype(mx.float32)
1031
+ mx.eval(weight)
1032
+ cached = (cache_key, weight)
1033
+ self._qwen3_5_decode_conv_weight = cached
1034
+
1035
+ weight = cached[1]
1036
+ return _qwen3_5_decode_depthwise_conv(conv_input, weight)
1037
+
1038
+ def _normalize_qk(self, q: mx.array, k: mx.array):
1039
+ inv_scale = k.shape[-1] ** -0.5
1040
+ q = (inv_scale**2) * mx.fast.rms_norm(q, None, 1e-6)
1041
+ k = inv_scale * mx.fast.rms_norm(k, None, 1e-6)
1042
+ return q, k
1043
+
1044
+ def _project_gates(self, inputs: mx.array):
1045
+ return self.in_proj_b(inputs), self.in_proj_a(inputs)
1046
+
1047
+ def __call__(
1048
+ self,
1049
+ inputs: mx.array,
1050
+ mask: Optional[mx.array] = None,
1051
+ cache: Optional[Any] = None,
1052
+ ) -> mx.array:
1053
+ B, S, _ = inputs.shape
1054
+ mixed_qkv = self.in_proj_qkv(inputs)
1055
+ z = self.in_proj_z(inputs)
1056
+ b, a = self._project_gates(inputs)
1057
+
1058
+ z = z.reshape(B, S, -1, self.head_v_dim)
1059
+
1060
+ if cache is not None and cache[0] is not None:
1061
+ conv_state = cache[0]
1062
+ if conv_state.shape[0] != B:
1063
+ conv_state = mx.zeros(
1064
+ (B, self.conv_kernel_size - 1, self.conv_dim),
1065
+ dtype=inputs.dtype,
1066
+ )
1067
+ else:
1068
+ conv_state = mx.zeros(
1069
+ (B, self.conv_kernel_size - 1, self.conv_dim),
1070
+ dtype=inputs.dtype,
1071
+ )
1072
+
1073
+ if mask is not None:
1074
+ if mask.shape[0] != B:
1075
+ mask = None
1076
+ else:
1077
+ mixed_qkv = mx.where(mask[..., None], mixed_qkv, 0)
1078
+ conv_input = mx.concatenate([conv_state, mixed_qkv], axis=1)
1079
+ if cache is not None:
1080
+ cache.update_window(
1081
+ 0, conv_input, self.conv_kernel_size - 1, lengths=cache.lengths
1082
+ )
1083
+ if (
1084
+ S == 1
1085
+ and conv_input.shape[1] == self.conv_kernel_size
1086
+ and self.conv1d.weight.dtype in (mx.bfloat16, mx.float16)
1087
+ ):
1088
+ conv_out = nn.silu(self._causal_conv1d_decode(conv_input))
1089
+ else:
1090
+ conv_out = nn.silu(self.conv1d(conv_input))
1091
+
1092
+ q, k, v = [
1093
+ t.reshape(B, S, h, d)
1094
+ for t, h, d in zip(
1095
+ mx.split(conv_out, [self.key_dim, 2 * self.key_dim], -1),
1096
+ [self.num_k_heads, self.num_k_heads, self.num_v_heads],
1097
+ [self.head_k_dim, self.head_k_dim, self.head_v_dim],
1098
+ )
1099
+ ]
1100
+
1101
+ q, k = self._normalize_qk(q, k)
1102
+
1103
+ out, _ = gated_delta_update(
1104
+ q,
1105
+ k,
1106
+ v,
1107
+ a,
1108
+ b,
1109
+ self.A_log,
1110
+ self.dt_bias,
1111
+ mask=mask,
1112
+ use_kernel=not self.training,
1113
+ cache=cache,
1114
+ )
1115
+
1116
+ if cache is not None:
1117
+ if hasattr(cache, "advance"):
1118
+ cache.advance(S)
1119
+ _qwen3_5_advance_lengths_info(cache, S)
1120
+
1121
+ out = self.norm(out, z)
1122
+ return self.out_proj(out.reshape(B, S, -1))
1123
+
1124
+
1125
+ class Qwen3_5DecoderLayer(nn.Module):
1126
+ def __init__(self, args: TextConfig, layer_idx: int):
1127
+ super().__init__()
1128
+ self.is_linear = (layer_idx + 1) % args.full_attention_interval != 0
1129
+ if self.is_linear:
1130
+ self.linear_attn = Qwen3_5GatedDeltaNet(args)
1131
+ else:
1132
+ self.self_attn = Qwen3_5Attention(args)
1133
+
1134
+ self.input_layernorm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps)
1135
+ self.post_attention_layernorm = nn.RMSNorm(
1136
+ args.hidden_size, eps=args.rms_norm_eps
1137
+ )
1138
+ self.mlp = Qwen3_5MLP(args.hidden_size, args.intermediate_size)
1139
+
1140
+ def __call__(
1141
+ self,
1142
+ x: mx.array,
1143
+ mask: Optional[mx.array] = None,
1144
+ cache: Optional[Any] = None,
1145
+ position_ids: Optional[mx.array] = None,
1146
+ position_embeddings: Optional[tuple[mx.array, mx.array]] = None,
1147
+ ) -> mx.array:
1148
+ if self.is_linear:
1149
+ r = self.linear_attn(
1150
+ self.input_layernorm(x),
1151
+ mask,
1152
+ cache,
1153
+ )
1154
+ else:
1155
+ r = self.self_attn(
1156
+ self.input_layernorm(x),
1157
+ mask=mask,
1158
+ cache=cache,
1159
+ position_ids=position_ids,
1160
+ position_embeddings=position_embeddings,
1161
+ )
1162
+ h = x + r
1163
+ return h + self.mlp(self.post_attention_layernorm(h))
1164
+
1165
+
1166
+ class Qwen3_5Model(nn.Module):
1167
+ def __init__(self, args: TextConfig):
1168
+ super().__init__()
1169
+ self.args = args
1170
+ self.embed_tokens = nn.Embedding(args.vocab_size, args.hidden_size)
1171
+ self.layers = [
1172
+ Qwen3_5DecoderLayer(args=args, layer_idx=i)
1173
+ for i in range(args.num_hidden_layers)
1174
+ ]
1175
+ self.norm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps)
1176
+ self.ssm_idx = 0
1177
+ self.fa_idx = args.full_attention_interval - 1
1178
+
1179
+ def __call__(
1180
+ self,
1181
+ inputs: mx.array,
1182
+ inputs_embeds: Optional[mx.array] = None,
1183
+ mask: Optional[mx.array] = None,
1184
+ cache=None,
1185
+ position_ids: Optional[mx.array] = None,
1186
+ capture_layer_ids: Optional[List[int]] = None,
1187
+ hidden_sink: Optional[list] = None,
1188
+ ):
1189
+ if inputs_embeds is None:
1190
+ h = self.embed_tokens(inputs)
1191
+ else:
1192
+ h = inputs_embeds
1193
+
1194
+ if cache is None:
1195
+ cache = [None] * len(self.layers)
1196
+
1197
+ fa_cache = cache[self.fa_idx]
1198
+ if (
1199
+ h.shape[0] == 1
1200
+ and hidden_sink is None
1201
+ and fa_cache is not None
1202
+ and _is_single_row_batch_cache(fa_cache)
1203
+ ):
1204
+ row_cache = []
1205
+ for cache_entry in cache:
1206
+ if cache_entry is None:
1207
+ row_cache.append(None)
1208
+ elif _is_single_row_batch_cache(cache_entry):
1209
+ row_cache.append(_extract_row_cache(cache_entry, 0))
1210
+ else:
1211
+ row_cache.append(cache_entry)
1212
+
1213
+ row_out = self(
1214
+ inputs,
1215
+ inputs_embeds=h,
1216
+ cache=row_cache,
1217
+ position_ids=position_ids,
1218
+ )
1219
+ for i, cache_entry in enumerate(row_cache):
1220
+ if cache[i] is None or cache_entry is None:
1221
+ continue
1222
+ if hasattr(cache[i].__class__, "merge"):
1223
+ cache[i] = cache[i].__class__.merge([cache_entry])
1224
+ return row_out
1225
+
1226
+ if (
1227
+ h.shape[0] > 1
1228
+ and h.shape[1] > 1
1229
+ and hidden_sink is None
1230
+ and fa_cache is not None
1231
+ and hasattr(fa_cache, "extract")
1232
+ and hasattr(fa_cache.__class__, "merge")
1233
+ and isinstance(getattr(fa_cache, "offset", None), mx.array)
1234
+ and fa_cache.offset.ndim > 0
1235
+ ):
1236
+ query_left_padding = mx.minimum(mx.maximum(-fa_cache.offset, 0), h.shape[1])
1237
+ cache_left_padding = getattr(fa_cache, "left_padding", None)
1238
+ has_left_padding = (
1239
+ isinstance(cache_left_padding, mx.array)
1240
+ and cache_left_padding.ndim > 0
1241
+ and int(cache_left_padding.max().item()) > 0
1242
+ )
1243
+ if has_left_padding or int(query_left_padding.max().item()) > 0:
1244
+ row_outputs = []
1245
+ row_caches = [[] for _ in cache]
1246
+ batch_offsets = []
1247
+ for cache_entry in cache:
1248
+ offsets = getattr(cache_entry, "offset", None)
1249
+ if (
1250
+ isinstance(offsets, mx.array)
1251
+ and offsets.ndim > 0
1252
+ and offsets.size >= h.shape[0]
1253
+ ):
1254
+ batch_offsets.append(offsets[: h.shape[0]])
1255
+ else:
1256
+ batch_offsets.append(None)
1257
+ for row, pad in enumerate(query_left_padding.tolist()):
1258
+ pad = min(max(int(pad), 0), h.shape[1])
1259
+ current_cache = []
1260
+ for cache_entry in cache:
1261
+ if cache_entry is None:
1262
+ current_cache.append(None)
1263
+ else:
1264
+ current_cache.append(_extract_row_cache(cache_entry, row))
1265
+ if pad == h.shape[1]:
1266
+ row_outputs.append(mx.zeros_like(h[row : row + 1]))
1267
+ for i, cache_entry in enumerate(current_cache):
1268
+ row_caches[i].append(cache_entry)
1269
+ continue
1270
+ row_inputs = inputs[row : row + 1, pad:]
1271
+ row_embeds = h[row : row + 1, pad:]
1272
+ row_position_ids = None
1273
+ if position_ids is not None:
1274
+ if position_ids.ndim == 2:
1275
+ row_position_ids = position_ids[row : row + 1, pad:]
1276
+ else:
1277
+ row_position_ids = position_ids[:, row : row + 1, pad:]
1278
+
1279
+ row_out = self(
1280
+ row_inputs,
1281
+ inputs_embeds=row_embeds,
1282
+ cache=current_cache,
1283
+ position_ids=row_position_ids,
1284
+ )
1285
+ if pad > 0:
1286
+ row_out = _pad_row_time(row_out, pad, h.shape[1])
1287
+ row_outputs.append(row_out)
1288
+ for i, cache_entry in enumerate(current_cache):
1289
+ row_caches[i].append(cache_entry)
1290
+
1291
+ for i, entries in enumerate(row_caches):
1292
+ if cache[i] is None:
1293
+ continue
1294
+ if hasattr(cache[i].__class__, "merge"):
1295
+ cache[i] = _restore_batch_padding_metadata(
1296
+ cache[i].__class__.merge(entries),
1297
+ batch_offsets[i],
1298
+ h.shape[1],
1299
+ )
1300
+ return mx.concatenate(row_outputs, axis=0)
1301
+
1302
+ fa_mask = _create_qwen3_5_attention_mask(h, cache[self.fa_idx])
1303
+ ssm_mask = _create_qwen3_5_ssm_mask(h, cache[self.ssm_idx])
1304
+ decode_left_padding = (
1305
+ getattr(cache[self.fa_idx], "_qwen3_5_decode_left_padding", None)
1306
+ if isinstance(fa_mask, str) and fa_mask == "left_padded_decode"
1307
+ else None
1308
+ )
1309
+ _set_qwen3_5_decode_left_padding(cache, self.layers, decode_left_padding)
1310
+
1311
+ position_embeddings = None
1312
+ if position_ids is not None:
1313
+ for layer in self.layers:
1314
+ if not layer.is_linear:
1315
+ if not layer.self_attn.rotary_emb.fused_apply:
1316
+ position_embeddings = layer.self_attn.rotary_emb(
1317
+ h, position_ids
1318
+ )
1319
+ break
1320
+
1321
+ capture_set = set(capture_layer_ids) if capture_layer_ids else set()
1322
+ for i, (layer, c) in enumerate(zip(self.layers, cache)):
1323
+ mask = ssm_mask if layer.is_linear else fa_mask
1324
+ h = layer(
1325
+ h,
1326
+ mask=mask,
1327
+ cache=c,
1328
+ position_ids=position_ids,
1329
+ position_embeddings=position_embeddings,
1330
+ )
1331
+ if hidden_sink is not None and i in capture_set:
1332
+ hidden_sink.append(h)
1333
+
1334
+ return self.norm(h)
1335
+
1336
+
1337
+ class LanguageModel(nn.Module):
1338
+ requires_uniform_batch_acceptance = True
1339
+
1340
+ def __init__(self, args: TextConfig, config: ModelConfig = None):
1341
+ super().__init__()
1342
+ self.args = args
1343
+ self.config = config
1344
+ self.model_type = args.model_type
1345
+ self.model = Qwen3_5Model(args)
1346
+ self._position_ids = None
1347
+ self._rope_deltas = None
1348
+
1349
+ if not args.tie_word_embeddings:
1350
+ self.lm_head = nn.Linear(args.hidden_size, args.vocab_size, bias=False)
1351
+
1352
+ def chunked_prefill_policy(
1353
+ self,
1354
+ *,
1355
+ input_ids=None,
1356
+ inputs_embeds=None,
1357
+ prompt_cache=None,
1358
+ draft_model=None,
1359
+ draft_kind=None,
1360
+ prefill_kwargs=None,
1361
+ ) -> bool:
1362
+ del input_ids, inputs_embeds, prompt_cache
1363
+ prefill_kwargs = prefill_kwargs or {}
1364
+ if draft_model is None:
1365
+ return True
1366
+ if draft_kind == "mtp":
1367
+ return bool(prefill_kwargs.get("return_hidden", False)) and bool(
1368
+ prefill_kwargs.get("return_shared_kv", False)
1369
+ )
1370
+ if draft_kind in ("dflash", "eagle3"):
1371
+ return prefill_kwargs.get("capture_layer_ids") is not None
1372
+ return draft_kind is None
1373
+
1374
+ def rollback_speculative_cache(
1375
+ self,
1376
+ caches: List[Any],
1377
+ rollback_state,
1378
+ accepted,
1379
+ block_size: int,
1380
+ ) -> int:
1381
+ return rollback_cache_transaction(
1382
+ caches,
1383
+ rollback_state,
1384
+ accepted,
1385
+ block_size,
1386
+ )
1387
+
1388
+ def get_rope_index(
1389
+ self,
1390
+ input_ids: mx.array,
1391
+ image_grid_thw: Optional[mx.array] = None,
1392
+ video_grid_thw: Optional[mx.array] = None,
1393
+ attention_mask: Optional[mx.array] = None,
1394
+ ):
1395
+ batch_size, seq_length = input_ids.shape
1396
+ position_ids = mx.arange(seq_length, dtype=mx.int32)
1397
+ position_ids = mx.broadcast_to(position_ids[None, :], (batch_size, seq_length))
1398
+ spatial_merge_size = self.config.vision_config.spatial_merge_size
1399
+ image_token_id = self.config.image_token_id
1400
+ video_token_id = self.config.video_token_id
1401
+ vision_start_token_id = self.config.vision_start_token_id
1402
+ mrope_position_deltas = []
1403
+ # The processor emits one vision block per temporal patch group, so
1404
+ # expand each video grid (t, h, w) into t rows of (1, h, w) — the same
1405
+ # split the reference implementation performs before indexing.
1406
+ if video_grid_thw is not None:
1407
+ rows = []
1408
+ for thw in video_grid_thw.tolist():
1409
+ rows.extend([[1, thw[1], thw[2]]] * int(thw[0]))
1410
+ video_grid_thw = mx.array(rows, dtype=mx.int32)
1411
+ if input_ids is not None and (
1412
+ image_grid_thw is not None or video_grid_thw is not None
1413
+ ):
1414
+ total_input_ids = input_ids
1415
+ if attention_mask is None:
1416
+ attention_mask = mx.ones_like(input_ids)
1417
+ position_ids = mx.ones(
1418
+ (3, input_ids.shape[0], input_ids.shape[1]), dtype=input_ids.dtype
1419
+ )
1420
+ image_index, video_index = 0, 0
1421
+ for i, input_ids in enumerate(total_input_ids):
1422
+ row_mask = attention_mask[i].tolist()
1423
+ input_tokens = [
1424
+ token
1425
+ for token, keep in zip(input_ids.tolist(), row_mask)
1426
+ if keep == 1
1427
+ ]
1428
+ image_nums, video_nums = 0, 0
1429
+ vision_tokens = [
1430
+ input_tokens[idx + 1]
1431
+ for idx, token in enumerate(input_tokens[:-1])
1432
+ if token == vision_start_token_id
1433
+ ]
1434
+ image_nums = sum(token == image_token_id for token in vision_tokens)
1435
+ video_nums = sum(token == video_token_id for token in vision_tokens)
1436
+ llm_pos_ids_list: list = []
1437
+ st = 0
1438
+ remain_images, remain_videos = image_nums, video_nums
1439
+ for _ in range(image_nums + video_nums):
1440
+ if image_token_id in input_tokens and remain_images > 0:
1441
+ ed_image = input_tokens.index(image_token_id, st)
1442
+ else:
1443
+ ed_image = len(input_tokens) + 1
1444
+ if video_token_id in input_tokens and remain_videos > 0:
1445
+ ed_video = input_tokens.index(video_token_id, st)
1446
+ else:
1447
+ ed_video = len(input_tokens) + 1
1448
+ if ed_image < ed_video:
1449
+ t, h, w = (
1450
+ image_grid_thw[image_index][0],
1451
+ image_grid_thw[image_index][1],
1452
+ image_grid_thw[image_index][2],
1453
+ )
1454
+ image_index += 1
1455
+ remain_images -= 1
1456
+ ed = ed_image
1457
+ else:
1458
+ t, h, w = (
1459
+ video_grid_thw[video_index][0],
1460
+ video_grid_thw[video_index][1],
1461
+ video_grid_thw[video_index][2],
1462
+ )
1463
+ video_index += 1
1464
+ remain_videos -= 1
1465
+ ed = ed_video
1466
+ llm_grid_t, llm_grid_h, llm_grid_w = (
1467
+ t.item(),
1468
+ h.item() // spatial_merge_size,
1469
+ w.item() // spatial_merge_size,
1470
+ )
1471
+ text_len = ed - st
1472
+ st_idx = (
1473
+ llm_pos_ids_list[-1].max() + 1
1474
+ if len(llm_pos_ids_list) > 0
1475
+ else 0
1476
+ )
1477
+ index = mx.arange(text_len).reshape(1, text_len)
1478
+ index = mx.broadcast_to(index, (3, text_len))
1479
+ index = index + st_idx
1480
+ llm_pos_ids_list.append(index)
1481
+ t_index = mx.arange(llm_grid_t).reshape(llm_grid_t, 1)
1482
+ t_index = mx.broadcast_to(
1483
+ t_index, (llm_grid_t, llm_grid_h * llm_grid_w)
1484
+ )
1485
+ t_index = t_index.flatten()
1486
+
1487
+ h_index = mx.arange(llm_grid_h).reshape(1, llm_grid_h, 1)
1488
+ h_index = mx.broadcast_to(
1489
+ h_index, (llm_grid_t, llm_grid_h, llm_grid_w)
1490
+ )
1491
+ h_index = h_index.flatten()
1492
+
1493
+ w_index = mx.arange(llm_grid_w).reshape(1, 1, llm_grid_w)
1494
+ w_index = mx.broadcast_to(
1495
+ w_index, (llm_grid_t, llm_grid_h, llm_grid_w)
1496
+ )
1497
+ w_index = w_index.flatten()
1498
+
1499
+ llm_pos_ids_list.append(
1500
+ mx.stack([t_index, h_index, w_index]) + text_len + st_idx
1501
+ )
1502
+ st = ed + llm_grid_t * llm_grid_h * llm_grid_w
1503
+ if st < len(input_tokens):
1504
+ st_idx = (
1505
+ llm_pos_ids_list[-1].max() + 1
1506
+ if len(llm_pos_ids_list) > 0
1507
+ else 0
1508
+ )
1509
+ text_len = len(input_tokens) - st
1510
+
1511
+ t_index = mx.arange(text_len).reshape(1, text_len)
1512
+ t_index = mx.broadcast_to(t_index, (3, text_len))
1513
+
1514
+ llm_pos_ids_list.append(t_index + st_idx)
1515
+
1516
+ if not llm_pos_ids_list:
1517
+ mrope_position_deltas.append(0)
1518
+ continue
1519
+
1520
+ llm_positions = mx.concatenate(llm_pos_ids_list, axis=1).reshape(3, -1)
1521
+ compact_max_position = llm_positions.max()
1522
+ padded_positions = [[1] * total_input_ids.shape[1] for _ in range(3)]
1523
+ compact_positions = llm_positions.tolist()
1524
+ compact_idx = 0
1525
+ for col, keep in enumerate(row_mask):
1526
+ if keep == 1:
1527
+ for dim in range(3):
1528
+ padded_positions[dim][col] = compact_positions[dim][
1529
+ compact_idx
1530
+ ]
1531
+ compact_idx += 1
1532
+ llm_positions = mx.array(padded_positions, dtype=position_ids.dtype)
1533
+ mask = mx.array(row_mask, dtype=mx.bool_)
1534
+ expanded_mask = mx.expand_dims(mask, axis=0)
1535
+ expanded_mask = mx.broadcast_to(expanded_mask, (3, 1, mask.shape[0]))
1536
+ expanded_positions = mx.expand_dims(llm_positions, axis=1)
1537
+ new_positions = mx.where(
1538
+ expanded_mask, expanded_positions, position_ids[:, i : i + 1, :]
1539
+ )
1540
+ updated_position_ids = mx.concatenate(
1541
+ [
1542
+ position_ids[:, :i, :],
1543
+ new_positions,
1544
+ position_ids[:, i + 1 :, :],
1545
+ ],
1546
+ axis=1,
1547
+ )
1548
+ position_ids = updated_position_ids
1549
+ mrope_position_deltas.append(
1550
+ compact_max_position + 1 - len(input_tokens)
1551
+ )
1552
+ mrope_position_deltas = mx.array(mrope_position_deltas).reshape(-1, 1)
1553
+ return position_ids, mrope_position_deltas
1554
+ else:
1555
+ if attention_mask is not None:
1556
+ position_ids = mx.cumsum(attention_mask.astype(mx.int64), axis=-1) - 1
1557
+ position_ids = mx.where(
1558
+ attention_mask == 0, mx.ones_like(position_ids), position_ids
1559
+ )
1560
+ max_position_ids = position_ids.max(axis=-1, keepdims=True)
1561
+ mrope_position_deltas = max_position_ids + 1 - attention_mask.shape[-1]
1562
+ else:
1563
+ position_ids = mx.arange(input_ids.shape[1]).reshape(1, -1)
1564
+ position_ids = mx.broadcast_to(
1565
+ position_ids, (input_ids.shape[0], input_ids.shape[1])
1566
+ )
1567
+ mrope_position_deltas = mx.zeros(
1568
+ [input_ids.shape[0], 1],
1569
+ dtype=input_ids.dtype,
1570
+ )
1571
+ return position_ids, mrope_position_deltas
1572
+
1573
+ def __call__(
1574
+ self,
1575
+ inputs: mx.array,
1576
+ inputs_embeds: Optional[mx.array] = None,
1577
+ mask: Optional[mx.array] = None,
1578
+ cache=None,
1579
+ **kwargs,
1580
+ ):
1581
+ position_ids = kwargs.pop("position_ids", None)
1582
+ pixel_values = kwargs.pop("pixel_values", None)
1583
+ image_grid_thw = kwargs.pop("image_grid_thw", None)
1584
+ video_grid_thw = kwargs.pop("video_grid_thw", None)
1585
+ attention_mask = kwargs.pop("attention_mask", None)
1586
+ capture_layer_ids = kwargs.pop("capture_layer_ids", None)
1587
+ speculative_verify = bool(kwargs.pop("speculative_verify", False))
1588
+ return_hidden = kwargs.pop("return_hidden", False)
1589
+ return_shared_kv = kwargs.pop("return_shared_kv", False)
1590
+ skip_logits = kwargs.pop("skip_logits", False)
1591
+ rope_deltas_kw = kwargs.pop("rope_deltas", None)
1592
+ if (
1593
+ mask is None
1594
+ and attention_mask is not None
1595
+ and attention_mask.shape[-1] == inputs.shape[-1]
1596
+ ):
1597
+ mask = attention_mask
1598
+ if pixel_values is not None:
1599
+ self._rope_deltas = None
1600
+ self._position_ids = None
1601
+
1602
+ if rope_deltas_kw is not None:
1603
+ self._rope_deltas = rope_deltas_kw
1604
+
1605
+ cache_offset = 0
1606
+ cache_offsets = None # per-element offsets for batched caches
1607
+ c0 = None
1608
+ if cache and cache[self.model.fa_idx] is not None:
1609
+ c0 = cache[self.model.fa_idx]
1610
+ cache_offset = c0._idx if hasattr(c0, "_idx") else c0.offset
1611
+ if (
1612
+ isinstance(c0.offset, mx.array)
1613
+ and c0.offset.ndim > 0
1614
+ and c0.offset.size > 1
1615
+ ):
1616
+ cache_offsets = mx.maximum(c0.offset, 0)
1617
+
1618
+ if position_ids is not None and cache_offsets is None:
1619
+ seq_length = inputs.shape[-1]
1620
+ if position_ids.shape[-1] > seq_length:
1621
+ position_ids = position_ids[
1622
+ ..., cache_offset : cache_offset + seq_length
1623
+ ]
1624
+
1625
+ if (
1626
+ mask is None
1627
+ and c0 is not None
1628
+ and cache_offsets is None
1629
+ and cache_offset == 0
1630
+ ):
1631
+ left_padding = getattr(c0, "left_padding", None)
1632
+ if (
1633
+ isinstance(left_padding, mx.array)
1634
+ and left_padding.ndim > 0
1635
+ and left_padding.size >= inputs.shape[0]
1636
+ ):
1637
+ positions = mx.arange(inputs.shape[-1])[None, :]
1638
+ mask = positions >= left_padding[: inputs.shape[0], None]
1639
+
1640
+ # Check if mask shape matches input shape (for chunked prefill compatibility)
1641
+ rope_mask = mask
1642
+ if mask is not None and mask.shape[-1] != inputs.shape[-1]:
1643
+ rope_mask = None
1644
+
1645
+ if position_ids is None and (rope_mask is None or rope_mask.ndim == 2):
1646
+ batch_size, seq_length = inputs.shape
1647
+
1648
+ if (
1649
+ (
1650
+ cache is not None
1651
+ and cache[self.model.fa_idx] is not None
1652
+ and (cache_offsets is None and cache_offset == 0)
1653
+ )
1654
+ or self._rope_deltas is None
1655
+ or cache is None
1656
+ ):
1657
+ if self._position_ids is not None:
1658
+ if (
1659
+ self._position_ids.ndim == 3
1660
+ and self._position_ids.shape[1] == batch_size
1661
+ and self._position_ids.shape[-1] >= cache_offset + seq_length
1662
+ ):
1663
+ position_ids = self._position_ids[
1664
+ :, :, cache_offset : cache_offset + seq_length
1665
+ ]
1666
+ elif (
1667
+ self._position_ids.ndim == 2
1668
+ and self._position_ids.shape[0] == batch_size
1669
+ and self._position_ids.shape[-1] >= cache_offset + seq_length
1670
+ ):
1671
+ position_ids = self._position_ids[
1672
+ :, cache_offset : cache_offset + seq_length
1673
+ ]
1674
+ else:
1675
+ position_ids, rope_deltas = self.get_rope_index(
1676
+ inputs, image_grid_thw, video_grid_thw, rope_mask
1677
+ )
1678
+ self._rope_deltas = rope_deltas
1679
+ self._position_ids = position_ids
1680
+ else:
1681
+ position_ids, rope_deltas = self.get_rope_index(
1682
+ inputs, image_grid_thw, video_grid_thw, rope_mask
1683
+ )
1684
+ if image_grid_thw is None and video_grid_thw is None:
1685
+ rope_deltas = mx.zeros((batch_size, 1), dtype=rope_deltas.dtype)
1686
+ self._rope_deltas = rope_deltas
1687
+ self._position_ids = position_ids
1688
+ else:
1689
+ rope_deltas_src = (
1690
+ rope_deltas_kw if rope_deltas_kw is not None else self._rope_deltas
1691
+ )
1692
+ if cache_offsets is not None and cache_offsets.size >= batch_size:
1693
+ offsets = cache_offsets[:batch_size]
1694
+ rope_deltas = rope_deltas_src
1695
+ if rope_deltas.shape[0] > batch_size:
1696
+ rope_deltas = rope_deltas[:batch_size]
1697
+ delta = (offsets + rope_deltas.squeeze(-1))[:, None]
1698
+ else:
1699
+ delta = mx.array(
1700
+ cache_offset + rope_deltas_src if cache is not None else 0
1701
+ )
1702
+ if delta.ndim == 0:
1703
+ delta = mx.expand_dims(delta, axis=0)
1704
+ if delta.shape[0] < batch_size:
1705
+ delta = mx.tile(delta, (batch_size, 1))
1706
+ else:
1707
+ delta = delta[:batch_size]
1708
+
1709
+ position_ids = mx.arange(seq_length).reshape(1, -1)
1710
+ position_ids = mx.broadcast_to(position_ids, (batch_size, seq_length))
1711
+ position_ids = mx.add(position_ids, delta)
1712
+ if (
1713
+ rope_deltas_kw is not None
1714
+ or self._position_ids is not None
1715
+ and self._position_ids.ndim == 3
1716
+ ):
1717
+ position_ids = position_ids[None, ...]
1718
+ position_ids = mx.broadcast_to(
1719
+ position_ids, (3, batch_size, seq_length)
1720
+ )
1721
+
1722
+ if speculative_verify:
1723
+ return _EXACT_SPECULATIVE_VERIFIER.verify(
1724
+ self,
1725
+ inputs,
1726
+ cache=cache,
1727
+ inputs_embeds=inputs_embeds,
1728
+ position_ids=position_ids,
1729
+ capture_layer_ids=capture_layer_ids,
1730
+ return_hidden=return_hidden,
1731
+ return_shared_kv=return_shared_kv,
1732
+ skip_logits=skip_logits,
1733
+ )
1734
+
1735
+ batch_invariant_decode = getattr(self, "_batch_invariant_decode", None)
1736
+ supports_batch_invariant_decode = getattr(
1737
+ self, "_supports_batch_invariant_decode", None
1738
+ )
1739
+ if (
1740
+ cache is not None
1741
+ and inputs.ndim == 2
1742
+ and inputs.shape[1] == 1
1743
+ and callable(batch_invariant_decode)
1744
+ and (
1745
+ supports_batch_invariant_decode is None
1746
+ or supports_batch_invariant_decode()
1747
+ )
1748
+ ):
1749
+ return batch_invariant_decode(
1750
+ inputs,
1751
+ cache=cache,
1752
+ inputs_embeds=inputs_embeds,
1753
+ position_ids=position_ids,
1754
+ skip_logits=skip_logits,
1755
+ )
1756
+
1757
+ hidden_sink: Optional[List[mx.array]] = (
1758
+ [] if capture_layer_ids is not None else None
1759
+ )
1760
+
1761
+ out = self.model(
1762
+ inputs,
1763
+ cache=cache,
1764
+ inputs_embeds=inputs_embeds,
1765
+ position_ids=position_ids,
1766
+ capture_layer_ids=capture_layer_ids,
1767
+ hidden_sink=hidden_sink,
1768
+ )
1769
+ if return_hidden:
1770
+ if hidden_sink is None:
1771
+ hidden_sink = []
1772
+ hidden_sink.append(out)
1773
+
1774
+ if skip_logits:
1775
+ logits = None
1776
+ elif self.args.tie_word_embeddings:
1777
+ logits = self.model.embed_tokens.as_linear(out)
1778
+ else:
1779
+ logits = self.lm_head(out)
1780
+ return LanguageModelOutput(
1781
+ logits=logits,
1782
+ hidden_states=hidden_sink,
1783
+ gdn_states=None,
1784
+ shared_kv_states={} if return_shared_kv else None,
1785
+ )
1786
+
1787
+ def speculative_logits_from_hidden(self, hidden: mx.array) -> mx.array:
1788
+ if self.args.tie_word_embeddings:
1789
+ return self.model.embed_tokens.as_linear(hidden)
1790
+ out = _EXACT_SPECULATIVE_VERIFIER.quantized_linear(self.lm_head, hidden)
1791
+ if out is not None:
1792
+ return out
1793
+ return self.lm_head(hidden)
1794
+
1795
+ def speculative_argmax_from_hidden(self, hidden: mx.array) -> Optional[mx.array]:
1796
+ if not self.args.tie_word_embeddings:
1797
+ out = _EXACT_SPECULATIVE_VERIFIER.quantized_argmax(self.lm_head, hidden)
1798
+ if out is not None:
1799
+ return out
1800
+ logits = self.speculative_logits_from_hidden(hidden)
1801
+ return mx.argmax(logits, axis=-1)
1802
+
1803
+ def supports_fused_greedy_logits_processors(self, logits_processors) -> bool:
1804
+ return (
1805
+ len(logits_processors) <= 4
1806
+ and all(
1807
+ processors
1808
+ and len(processors) == 1
1809
+ and callable(getattr(processors[0], "prepare_next_token_mask", None))
1810
+ for processors in logits_processors
1811
+ )
1812
+ and not self.args.tie_word_embeddings
1813
+ and _EXACT_SPECULATIVE_VERIFIER.can_quantized_head(self.lm_head)
1814
+ and "bias" not in self.lm_head
1815
+ )
1816
+
1817
+ def fused_greedy_decode(
1818
+ self,
1819
+ inputs: mx.array,
1820
+ cache=None,
1821
+ logits_processors=None,
1822
+ **kwargs,
1823
+ ):
1824
+ if (
1825
+ self.args.tie_word_embeddings
1826
+ or not _EXACT_SPECULATIVE_VERIFIER.can_quantized_head(self.lm_head)
1827
+ or "bias" in self.lm_head
1828
+ ):
1829
+ return None
1830
+
1831
+ token_mask = None
1832
+ if logits_processors:
1833
+ if not self.supports_fused_greedy_logits_processors(logits_processors):
1834
+ return None
1835
+ token_mask = mx.concatenate(
1836
+ [
1837
+ processors[0].prepare_next_token_mask(token)
1838
+ for processors, token in zip(
1839
+ logits_processors, inputs[:, -1].tolist()
1840
+ )
1841
+ ],
1842
+ axis=0,
1843
+ )
1844
+ token_mask = _EXACT_SPECULATIVE_VERIFIER.pad_token_mask(
1845
+ token_mask, self.lm_head.weight.shape[0]
1846
+ )
1847
+
1848
+ output = self(
1849
+ inputs,
1850
+ cache=cache,
1851
+ return_hidden=True,
1852
+ skip_logits=True,
1853
+ **kwargs,
1854
+ )
1855
+ hidden = output.hidden_states[-1]
1856
+ sampled = _EXACT_SPECULATIVE_VERIFIER.quantized_argmax(
1857
+ self.lm_head, hidden, token_mask=token_mask
1858
+ )
1859
+ if sampled is not None:
1860
+ return sampled
1861
+ if token_mask is not None:
1862
+ raise RuntimeError("masked fused greedy decode became unsupported")
1863
+ return mx.argmax(self.speculative_logits_from_hidden(hidden), axis=-1)
1864
+
1865
+ def speculative_verify_logits(self, inputs: mx.array, cache, sampler):
1866
+ out = self(
1867
+ inputs,
1868
+ cache=cache,
1869
+ capture_layer_ids=[],
1870
+ speculative_verify=True,
1871
+ return_hidden=True,
1872
+ return_shared_kv=True,
1873
+ )
1874
+ try:
1875
+ return (
1876
+ out.hidden_states[-1],
1877
+ out.shared_kv_states,
1878
+ out.gdn_states,
1879
+ sampler(out.logits),
1880
+ )
1881
+ except BaseException:
1882
+ out.gdn_states.abort()
1883
+ raise
1884
+
1885
+ def speculative_verify_hidden(self, inputs: mx.array, cache):
1886
+ out = self(
1887
+ inputs,
1888
+ cache=cache,
1889
+ capture_layer_ids=[],
1890
+ speculative_verify=True,
1891
+ return_hidden=True,
1892
+ return_shared_kv=True,
1893
+ skip_logits=True,
1894
+ )
1895
+ return out.hidden_states[-1], out.shared_kv_states, out.gdn_states
1896
+
1897
+ @property
1898
+ def layers(self):
1899
+ return self.model.layers
1900
+
1901
+ def make_cache(self):
1902
+ return [ArraysCache(size=2) if l.is_linear else KVCache() for l in self.layers]
1903
+
1904
+ @property
1905
+ def head_dim(self):
1906
+ return self.args.hidden_size // self.args.num_attention_heads
1907
+
1908
+ @property
1909
+ def n_kv_heads(self):
1910
+ return self.args.num_key_value_heads
1911
+
1912
+ @property
1913
+ def quant_predicate(self):
1914
+
1915
+ if getattr(self.args, "num_experts", 0) <= 0:
1916
+ return None
1917
+
1918
+ def predicate(path, _):
1919
+ if path.endswith("mlp.gate") or path.endswith("shared_expert_gate"):
1920
+ return {"group_size": 64, "bits": 8}
1921
+ return True
1922
+
1923
+ return predicate
1924
+
1925
+ @property
1926
+ def cast_predicate(self):
1927
+ def predicate(path: str):
1928
+ if path.endswith("A_log"):
1929
+ return False
1930
+ return True
1931
+
1932
+ return predicate
mlx_agent_tools/raw/upstream/qwen3_5.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ import mlx.core as mx
4
+ import mlx.nn as nn
5
+
6
+ from ..base import InputEmbeddingsFeatures
7
+ from ..qwen3_vl import Model as Qwen3VLModel
8
+ from ..qwen3_vl import processing_qwen3_vl # noqa: F401
9
+ from ..qwen3_vl.qwen3_vl import masked_scatter
10
+ from .config import ModelConfig
11
+ from .language import LanguageModel
12
+ from .vision import VisionModel
13
+
14
+
15
+ def sanitize_key(key):
16
+ if key.startswith("model.language_model.visual"):
17
+ key = key.replace("model.language_model.visual", "vision_tower", 1)
18
+ elif key.startswith("model.language_model"):
19
+ key = key.replace("model.language_model", "language_model.model", 1)
20
+ elif key.startswith("model.visual"):
21
+ key = key.replace("model.visual", "vision_tower", 1)
22
+ elif key.startswith("lm_head"):
23
+ key = key.replace("lm_head", "language_model.lm_head", 1)
24
+ return key
25
+
26
+
27
+ NORM_WEIGHT_SUFFIXES = (
28
+ ".input_layernorm.weight",
29
+ ".post_attention_layernorm.weight",
30
+ "model.norm.weight",
31
+ ".q_norm.weight",
32
+ ".k_norm.weight",
33
+ )
34
+
35
+
36
+ def should_shift_norm_weights(weights):
37
+ has_mtp_weights = any("mtp." in key for key in weights)
38
+ has_unsanitized_conv1d = any(
39
+ "conv1d.weight" in key and value.shape[-1] != 1
40
+ for key, value in weights.items()
41
+ )
42
+ return has_mtp_weights or has_unsanitized_conv1d
43
+
44
+
45
+ def should_offset_norm_weight(original_key, shift_norm_weights):
46
+ return shift_norm_weights or not original_key.startswith("language_model.")
47
+
48
+
49
+ class Model(Qwen3VLModel):
50
+
51
+ def __init__(self, config: ModelConfig):
52
+ # only initialize nn.Module, skip the initialization of vision_tower and language_model in the parent class
53
+ nn.Module.__init__(self)
54
+ self.config = config
55
+ self.vision_tower = VisionModel(config.vision_config)
56
+ self.language_model = LanguageModel(config.text_config, config)
57
+
58
+ def get_input_embeddings(
59
+ self,
60
+ input_ids: Optional[mx.array] = None,
61
+ pixel_values: Optional[mx.array] = None,
62
+ **kwargs,
63
+ ):
64
+ if pixel_values is None:
65
+ pixel_values = kwargs.get("pixel_values_videos", None)
66
+
67
+ image_grid_thw = kwargs.get("image_grid_thw", None)
68
+ video_grid_thw = kwargs.get("video_grid_thw", None)
69
+ mask = kwargs.get("mask", None)
70
+ grid_thw = image_grid_thw if image_grid_thw is not None else video_grid_thw
71
+
72
+ if pixel_values is None:
73
+ position_ids, rope_deltas = self.language_model.get_rope_index(
74
+ input_ids, attention_mask=mask
75
+ )
76
+ return InputEmbeddingsFeatures(
77
+ inputs_embeds=self.language_model.model.embed_tokens(input_ids),
78
+ position_ids=position_ids,
79
+ rope_deltas=rope_deltas,
80
+ )
81
+
82
+ dtype = self.vision_tower.patch_embed.proj.weight.dtype
83
+ pixel_values = pixel_values.astype(dtype)
84
+
85
+ # Get the input embeddings from the language model
86
+ inputs_embeds = self.language_model.model.embed_tokens(input_ids)
87
+
88
+ vision_cache = kwargs.get("vision_cache", None)
89
+ cached = kwargs.get("cached_image_features", None)
90
+ if cached is None and vision_cache is not None:
91
+ cached = vision_cache.get(kwargs.get("_image_key"))
92
+ if cached is not None:
93
+ hidden_states = cached
94
+ else:
95
+ # Get the ouptut hidden states from the vision model
96
+ hidden_states, _ = self.vision_tower(pixel_values, grid_thw)
97
+ if vision_cache is not None and kwargs.get("_image_key") is not None:
98
+ mx.eval(hidden_states)
99
+ vision_cache.put(kwargs["_image_key"], hidden_states)
100
+
101
+ # Insert special image tokens in the input_ids
102
+ inputs_embeds, _ = self.merge_input_ids_with_image_features(
103
+ hidden_states,
104
+ inputs_embeds,
105
+ input_ids,
106
+ self.config.image_token_index,
107
+ self.config.video_token_index,
108
+ )
109
+
110
+ position_ids, rope_deltas = self.language_model.get_rope_index(
111
+ input_ids, image_grid_thw, video_grid_thw, mask
112
+ )
113
+
114
+ return InputEmbeddingsFeatures(
115
+ inputs_embeds=inputs_embeds,
116
+ position_ids=position_ids,
117
+ rope_deltas=rope_deltas,
118
+ )
119
+
120
+ @staticmethod
121
+ def merge_input_ids_with_image_features(
122
+ image_features, inputs_embeds, input_ids, image_token_index, video_token_index
123
+ ):
124
+ special_image_mask = input_ids == image_token_index
125
+ special_video_mask = input_ids == video_token_index
126
+ special_image_mask = special_image_mask | special_video_mask
127
+ n_image_tokens = special_image_mask.sum()
128
+ special_image_mask = special_image_mask[..., None]
129
+ special_image_mask = mx.broadcast_to(special_image_mask, inputs_embeds.shape)
130
+
131
+ n_image_features = image_features.shape[0]
132
+ n_image_mask_elements = special_image_mask.sum()
133
+ if n_image_mask_elements != image_features.size:
134
+ raise ValueError(
135
+ f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
136
+ )
137
+
138
+ inputs_embeds = masked_scatter(
139
+ inputs_embeds, special_image_mask, image_features
140
+ )
141
+
142
+ return inputs_embeds, special_image_mask
143
+
144
+ def sanitize(self, weights):
145
+ # The MTP draft shard is separate from the base model. Its presence
146
+ # must not select the base model's RMSNorm loading convention.
147
+ weights = {key: value for key, value in weights.items() if "mtp." not in key}
148
+ shift_norm_weights = should_shift_norm_weights(weights)
149
+
150
+ if self.config.text_config.tie_word_embeddings:
151
+ weights.pop("lm_head.weight", None)
152
+
153
+ sanitized_weights = {}
154
+ for key, value in weights.items():
155
+ original_key = key
156
+ key = sanitize_key(key)
157
+
158
+ if "conv1d.weight" in key and value.shape[-1] != 1:
159
+ value = value.moveaxis(2, 1)
160
+ # Qwen3.8 ships the Conv3d patch embed in PyTorch NCDHW order,
161
+ # while MLX convolutions expect NDHWC. Guard on the trailing axis
162
+ # so re-sanitizing already-converted weights is a no-op.
163
+ if key.endswith("patch_embed.proj.weight") and value.ndim == 5:
164
+ in_ch = self.config.vision_config.in_channels
165
+ if value.shape[-1] != in_ch and value.shape[1] == in_ch:
166
+ value = value.transpose(0, 2, 3, 4, 1)
167
+ if any(key.endswith(sfx) for sfx in NORM_WEIGHT_SUFFIXES):
168
+ if value.ndim == 1 and should_offset_norm_weight(
169
+ original_key, shift_norm_weights
170
+ ):
171
+ value += 1.0
172
+
173
+ sanitized_weights[key] = value
174
+
175
+ return sanitized_weights
176
+
177
+ @property
178
+ def quant_predicate(self):
179
+ return self.language_model.quant_predicate
180
+
181
+ @property
182
+ def cast_predicate(self):
183
+ return self.language_model.cast_predicate
mlx_agent_tools/redacting_log.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Emit process logs without exposing model service credentials."""
2
+ from __future__ import annotations
3
+
4
+ class SecretLogStream:
5
+ def __init__(self,stream,secret):
6
+ self.stream=stream
7
+ self.secret=secret
8
+ self.pending=''
9
+ def write(self,text):
10
+ self.pending+=text
11
+ while '\n' in self.pending:
12
+ line,self.pending=self.pending.split('\n',1)
13
+ self.stream.write(line.replace(self.secret,'[redacted]')+'\n')
14
+ return len(text)
15
+ def flush(self):
16
+ # Keep partial lines private so fragmented tokens cannot evade redaction.
17
+ self.stream.flush()
18
+ def isatty(self):return False
19
+ @property
20
+ def encoding(self):return getattr(self.stream,'encoding',None) or 'utf-8'
21
+ def fileno(self):return self.stream.fileno()
mlx_agent_tools/separate_mtp.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Separate normalized embedded MTP by byte-preserving safetensors repack.
2
+
3
+ Avoids mlx-lm's presence-keyed RMSNorm shift on a converted trunk. No inference,
4
+ quantization, normalization, provider selection or source mutation is performed.
5
+ """
6
+ from pathlib import Path
7
+ import argparse,hashlib,json,os,shutil,struct
8
+
9
+
10
+ def header(path):
11
+ with path.open('rb') as f:
12
+ length=struct.unpack('<Q',f.read(8))[0]
13
+ if length>16*1024**2:raise ValueError('Header size limit')
14
+ data=json.loads(f.read(length))
15
+ return data,8+length
16
+
17
+
18
+ def repack(output,entries,heads):
19
+ metadata={'__metadata__':{'format':'mlx'}};cursor=0
20
+ for newname,src,old,base,key in entries:
21
+ start,end=old['data_offsets'];metadata[newname]={**old,'data_offsets':[cursor,cursor+end-start]};cursor+=end-start
22
+ raw=json.dumps(metadata,separators=(',',':')).encode();raw+=b' '*(-len(raw)%8);digests={}
23
+ with output.open('xb') as out:
24
+ out.write(struct.pack('<Q',len(raw)));out.write(raw)
25
+ for newname,src,old,base,key in entries:
26
+ start,end=old['data_offsets'];count=end-start;digest=hashlib.sha256()
27
+ with src.open('rb') as source:
28
+ source.seek(base+start)
29
+ while count:
30
+ chunk=source.read(min(count,8*1024**2))
31
+ if not chunk:raise ValueError('Truncated tensor')
32
+ out.write(chunk);digest.update(chunk);count-=len(chunk)
33
+ digests[newname]={'source_tensor':key,'payload_sha256':digest.hexdigest(),'payload_bytes':end-start}
34
+ return digests,cursor
35
+
36
+
37
+ def prepare(source,output):
38
+ source,output=Path(source).resolve(),Path(output).resolve()
39
+ if output.exists() or source==output or source in output.parents:raise ValueError('Output exists or inside source')
40
+ index=json.loads((source/'model.safetensors.index.json').read_text())['weight_map'];heads=[k for k in index if k.startswith('language_model.mtp.') or k.startswith('mtp.')]
41
+ if not heads:raise ValueError('No embedded MTP tensors')
42
+ schemas={}
43
+ for filename in sorted(set(index.values())):
44
+ if Path(filename).name!=filename:raise ValueError('Unsafe source shard')
45
+ h,base=header(source/filename);keys={k for k in h if k!='__metadata__'}
46
+ if keys!={k for k,v in index.items() if v==filename}:raise ValueError('Index/header mismatch')
47
+ if h.get('__metadata__',{}).get('format')!='mlx':raise ValueError('Source not marked normalized MLX format')
48
+ schemas[filename]=(h,base)
49
+ output.mkdir();mapping={};allhead=[];payloads={};total=0
50
+ for filename,(h,base) in schemas.items():
51
+ selected=[k for k,v in index.items() if v==filename];trunk=[k for k in selected if k not in heads]
52
+ for key in selected:
53
+ if key in heads:
54
+ newname=key.removeprefix('language_model.')
55
+ allhead.append((newname,source/filename,h[key],base,key))
56
+ if not trunk:continue
57
+ if len(trunk)==len(selected):
58
+ os.link(source/filename,output/filename)
59
+ total+=sum(h[k]['data_offsets'][1]-h[k]['data_offsets'][0] for k in trunk)
60
+ else:
61
+ entries=[(k,source/filename,h[k],base,k) for k in trunk]
62
+ d,size=repack(output/filename,entries,heads);payloads.update(d);total+=size
63
+ mapping.update({k:filename for k in trunk})
64
+ d,size=repack(output/'mtp.safetensors',allhead,heads);payloads.update(d)
65
+ for p in source.iterdir():
66
+ if p.is_file() and p.suffix in ['.json','.jinja','.txt','.md'] and p.name not in ['model.safetensors.index.json']:
67
+ shutil.copy2(p,output/p.name)
68
+ (output/'model.safetensors.index.json').write_text(json.dumps({'metadata':{'total_size':total},'weight_map':mapping},indent=2)+'\n')
69
+ # Verify every rewritten payload independently against the copied digest.
70
+ for filename in [*{index[k] for k in heads if index[k] in mapping.values()},'mtp.safetensors']:
71
+ p=output/filename
72
+ if not p.exists():continue
73
+ h,base=header(p)
74
+ with p.open('rb') as f:
75
+ for name,record in h.items():
76
+ if name=='__metadata__':continue
77
+ start,end=record['data_offsets'];f.seek(base+start);remaining=end-start;digest=hashlib.sha256()
78
+ while remaining:
79
+ block=f.read(min(remaining,8*1024**2));digest.update(block);remaining-=len(block)
80
+ if digest.hexdigest()!=payloads[name]['payload_sha256']:raise ValueError('Repacked tensor hash mismatch')
81
+ receipt={'method':'exact tensor-payload repack only; no numerical change',
82
+ 'source':str(source),'base_tensors':len(mapping),'mtp_tensors':len(heads),'payload_hashes':payloads,
83
+ 'norm_shift_applied':False,'quantization_changed':False,'source_unchanged':True}
84
+ (output/'mtp-separation-manifest.json').write_text(json.dumps(receipt,indent=2)+'\n');return receipt
85
+
86
+ if __name__=='__main__':
87
+ p=argparse.ArgumentParser();p.add_argument('--source',type=Path,required=True);p.add_argument('--output',type=Path,required=True);a=p.parse_args();r=prepare(a.source,a.output);print({k:r[k] for k in ['base_tensors','mtp_tensors','norm_shift_applied','quantization_changed']})
mlx_agent_tools/stream_convert.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bounded CPU Coder390 BF16 -> MLX affine q4 conversion; never loads a model.
2
+
3
+ Sanitization is delegated to a SHA-pinned upstream mlx-vlm implementation.
4
+ Each source is fully hashed before use; source weights are never modified.
5
+ MTP remains in the source for a separate native sidecar extraction.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import gc
11
+ import hashlib
12
+ import importlib.util
13
+ import json
14
+ import math
15
+ from pathlib import Path
16
+ import shutil
17
+ import struct
18
+ import time
19
+ from types import SimpleNamespace
20
+
21
+ import mlx.core as mx
22
+ import numpy as np
23
+
24
+ ROOT = Path(__file__).resolve().parent
25
+ SANITIZER = ROOT / "raw/upstream/qwen3_5.py"
26
+ SANITIZER_SHA = "7c0e360a35e1f5d3819677cd6f7e4d7349f4f3dd2fad5fc8f1e374bd514e8f1b"
27
+ SANITIZER_REV = "952d4f6bc65bd5095e74abe71c78038764ee08aa"
28
+ DTYPES = {"BF16": (np.dtype("<u2"), mx.bfloat16),
29
+ "F32": (np.dtype("<f4"), mx.float32),
30
+ "F16": (np.dtype("<f2"), mx.float16)}
31
+ LINEAR_SUFFIXES = (".mlp.up_proj.weight", ".mlp.gate_proj.weight", ".mlp.down_proj.weight",
32
+ ".self_attn.q_proj.weight", ".self_attn.k_proj.weight", ".self_attn.v_proj.weight",
33
+ ".self_attn.o_proj.weight", ".linear_attn.in_proj_qkv.weight",
34
+ ".linear_attn.in_proj_z.weight", ".linear_attn.in_proj_a.weight",
35
+ ".linear_attn.in_proj_b.weight", ".linear_attn.out_proj.weight",
36
+ ".embed_tokens.weight", "lm_head.weight")
37
+
38
+
39
+ def sha256(path):
40
+ digest = hashlib.sha256()
41
+ with Path(path).open("rb") as handle:
42
+ for block in iter(lambda: handle.read(8 * 1024 * 1024), b""):
43
+ digest.update(block)
44
+ return digest.hexdigest()
45
+
46
+
47
+ def sanitizer():
48
+ if sha256(SANITIZER) != SANITIZER_SHA:
49
+ raise ValueError("Pinned sanitizer hash mismatch")
50
+ spec = importlib.util.spec_from_file_location("mlx_vlm.models.qwen3_5._coder390_sanitize", SANITIZER)
51
+ module = importlib.util.module_from_spec(spec)
52
+ spec.loader.exec_module(module)
53
+ return module.Model.sanitize
54
+
55
+
56
+ def read_header(path):
57
+ with path.open("rb") as handle:
58
+ prefix = handle.read(8)
59
+ if len(prefix) != 8:
60
+ raise ValueError("Truncated safetensors header")
61
+ length = struct.unpack("<Q", prefix)[0]
62
+ if length > 16 * 1024 * 1024:
63
+ raise ValueError("Safetensors header bound exceeded")
64
+ raw = handle.read(length)
65
+ if len(raw) != length:
66
+ raise ValueError("Truncated safetensors header")
67
+ header = json.loads(raw)
68
+ entries = {key: value for key, value in header.items() if key != "__metadata__"}
69
+ payload = path.stat().st_size - length - 8
70
+ spans = []
71
+ for key, meta in entries.items():
72
+ if meta["dtype"] not in DTYPES:
73
+ raise ValueError(f"Unsupported source dtype: {key}: {meta['dtype']}")
74
+ start, end = meta["data_offsets"]
75
+ shape = meta["shape"]
76
+ if any(type(n) is not int or n < 0 for n in shape):
77
+ raise ValueError(f"Invalid tensor shape: {key}")
78
+ size = math.prod(shape) * DTYPES[meta["dtype"]][0].itemsize
79
+ if start < 0 or end - start != size or end > payload:
80
+ raise ValueError(f"Invalid source tensor offsets: {key}")
81
+ spans.append((start, end))
82
+ spans.sort()
83
+ cursor = 0
84
+ for start, end in spans:
85
+ if start != cursor:
86
+ raise ValueError("Safetensors payload gaps or overlaps")
87
+ cursor = end
88
+ if cursor != payload:
89
+ raise ValueError("Safetensors payload size mismatch")
90
+ return entries, 8 + length
91
+
92
+
93
+ def quantizable(name, shape):
94
+ if name.startswith("model.visual."):
95
+ return False
96
+ if name.startswith("mtp."):
97
+ return False
98
+ if len(shape) == 2 and name.endswith(LINEAR_SUFFIXES):
99
+ if shape[-1] % 64:
100
+ raise ValueError(f"Unsupported group alignment: {name}")
101
+ return True
102
+ known = (".input_layernorm.weight", ".post_attention_layernorm.weight", ".norm.weight",
103
+ ".q_norm.weight", ".k_norm.weight", ".conv1d.weight", ".A_log", ".dt_bias")
104
+ if name.endswith(known):
105
+ return False
106
+ raise ValueError(f"Unsupported/unknown source tensor: {name}")
107
+
108
+
109
+ def tensor_bytes(array):
110
+ mx.eval(array)
111
+ dtype = array.dtype
112
+ if dtype == mx.bfloat16:
113
+ return np.asarray(array.view(mx.uint16), dtype="<u2").tobytes(), "BF16"
114
+ if dtype == mx.float32:
115
+ return np.asarray(array, dtype="<f4").tobytes(), "F32"
116
+ if dtype == mx.float16:
117
+ return np.asarray(array, dtype="<f2").tobytes(), "F16"
118
+ if dtype == mx.uint32:
119
+ return np.asarray(array, dtype="<u4").tobytes(), "U32"
120
+ raise ValueError(f"Unsupported output dtype: {dtype}")
121
+
122
+
123
+ def pack_shard(output, pending, sequence):
124
+ filename = f"model-{sequence:05d}.safetensors"
125
+ header = {"__metadata__": {"format": "mlx"}}
126
+ offset = 0
127
+ for record in pending:
128
+ end = offset + record["bytes"]
129
+ header[record["name"]] = {"dtype": record["dtype"], "shape": record["shape"],
130
+ "data_offsets": [offset, end]}
131
+ offset = end
132
+ raw = json.dumps(header, separators=(",", ":")).encode()
133
+ raw += b" " * ((-len(raw)) % 8)
134
+ path = output / filename
135
+ with path.open("xb") as handle:
136
+ handle.write(struct.pack("<Q", len(raw)))
137
+ handle.write(raw)
138
+ for record in pending:
139
+ with record["path"].open("rb") as source:
140
+ shutil.copyfileobj(source, handle, 8 * 1024 * 1024)
141
+ record["path"].unlink()
142
+ return filename
143
+
144
+
145
+ def convert(source, output, expected, *, row_chunk=128, shard_bytes=512 * 1024 * 1024):
146
+ mx.set_default_device(mx.cpu)
147
+ source, output = Path(source).resolve(), Path(output).resolve()
148
+ if output.exists() or output == source or source in output.parents:
149
+ raise ValueError("Destination exists or is inside source; refusing overwrite")
150
+ if not 1 <= row_chunk <= 512:
151
+ raise ValueError("row_chunk must be in 1..512")
152
+ index = json.loads((source / "model.safetensors.index.json").read_text())["weight_map"]
153
+ config = json.loads((source / "config.json").read_text())
154
+ source_records = {}
155
+ headers = {}
156
+ for filename in sorted(set(index.values())):
157
+ if Path(filename).name != filename:
158
+ raise ValueError("Unsafe source shard path")
159
+ path = source / filename
160
+ want = expected.get(filename)
161
+ if not want or path.stat().st_size != want["size"]:
162
+ raise ValueError(f"Source size/manifest mismatch: {filename}")
163
+ print(f"Verifying full SHA-256: {filename}", flush=True)
164
+ digest = sha256(path)
165
+ if digest != want["sha256"]:
166
+ raise ValueError(f"Source SHA-256 mismatch: {filename}")
167
+ source_records[filename] = {"size": path.stat().st_size, "sha256": digest}
168
+ headers[filename] = read_header(path)
169
+ if set(headers[filename][0]) != {key for key, value in index.items() if value == filename}:
170
+ raise ValueError(f"Index/header mismatch: {filename}")
171
+ output.mkdir(parents=True)
172
+ spool = output / ".tensor-spool"
173
+ spool.mkdir()
174
+ sanitize = sanitizer()
175
+ owner = SimpleNamespace(config=SimpleNamespace(
176
+ text_config=SimpleNamespace(tie_word_embeddings=config["text_config"].get("tie_word_embeddings", False)),
177
+ vision_config=SimpleNamespace(in_channels=config.get("vision_config", {}).get("in_channels", 3))))
178
+ pending, weight_map, transforms = [], {}, []
179
+ total_size, sequence, spool_id = 0, 1, 0
180
+ started = time.monotonic()
181
+ for number, (name, filename) in enumerate(index.items(), 1):
182
+ if name.startswith("mtp."):
183
+ continue
184
+ meta, base = headers[filename]
185
+ meta = meta[name]
186
+ shape = meta["shape"]
187
+ do_quant = quantizable(name, shape)
188
+ dtype_np, dtype_mx = DTYPES[meta["dtype"]]
189
+ mapped = np.memmap(source / filename, dtype=dtype_np, mode="r",
190
+ offset=base + meta["data_offsets"][0], shape=tuple(shape))
191
+ rows = shape[0] if shape else 1
192
+ records = {}
193
+ for start in range(0, rows, row_chunk):
194
+ part = np.array(mapped[start:start + row_chunk] if shape else mapped, copy=True)
195
+ array = mx.array(part)
196
+ if dtype_mx == mx.bfloat16:
197
+ array = array.view(mx.bfloat16)
198
+ if not bool(mx.all(mx.isfinite(array))):
199
+ raise ValueError(f"Nonfinite source tensor: {name}")
200
+ clean = sanitize(owner, {name: array})
201
+ if len(clean) != 1:
202
+ raise ValueError(f"Unexpected sanitizer output: {name}")
203
+ new_name, array = next(iter(clean.items()))
204
+ if do_quant:
205
+ q, scale, bias = mx.quantize(array, group_size=64, bits=4, mode="affine")
206
+ values = {new_name: q, new_name.removesuffix(".weight") + ".scales": scale,
207
+ new_name.removesuffix(".weight") + ".biases": bias}
208
+ else:
209
+ values = {new_name: array}
210
+ for key, value in values.items():
211
+ if not bool(mx.all(mx.isfinite(value))):
212
+ raise ValueError(f"Nonfinite converted tensor: {key}")
213
+ data, kind = tensor_bytes(value)
214
+ if key not in records:
215
+ spool_id += 1
216
+ path = spool / f"{spool_id:06d}.payload"
217
+ records[key] = {"name": key, "dtype": kind, "shape": list(value.shape), "bytes": 0, "path": path}
218
+ if shape:
219
+ records[key]["shape"][0] = 0
220
+ record = records[key]
221
+ if shape:
222
+ record["shape"][0] += value.shape[0]
223
+ with record["path"].open("ab") as handle:
224
+ handle.write(data)
225
+ record["bytes"] += len(data)
226
+ del array, clean, values, part
227
+ if do_quant:
228
+ del q, scale, bias
229
+ del value, data
230
+ del mapped
231
+ new_records = list(records.values())
232
+ size = sum(record["bytes"] for record in new_records)
233
+ if pending and sum(record["bytes"] for record in pending) + size > shard_bytes:
234
+ shard = pack_shard(output, pending, sequence)
235
+ for record in pending:
236
+ weight_map[record["name"]] = shard
237
+ pending = []
238
+ sequence += 1
239
+ pending.extend(new_records)
240
+ total_size += size
241
+ transforms.append({"source": name, "output": list(records), "quantized": do_quant})
242
+ gc.collect()
243
+ print(f"Converted {number}/{len(index)} {name} -> {size} bytes (CPU)", flush=True)
244
+ if pending:
245
+ shard = pack_shard(output, pending, sequence)
246
+ for record in pending:
247
+ if record["name"] in weight_map:
248
+ raise ValueError("Duplicate converted tensor name")
249
+ weight_map[record["name"]] = shard
250
+ spool.rmdir()
251
+ index_out = {"metadata": {"total_size": total_size}, "weight_map": dict(sorted(weight_map.items()))}
252
+ (output / "model.safetensors.index.json").write_text(json.dumps(index_out, indent=2) + "\n")
253
+ quantization = {"group_size": 64, "bits": 4, "mode": "affine"}
254
+ config["quantization"] = quantization
255
+ config["quantization_config"] = dict(quantization)
256
+ (output / "config.json").write_text(json.dumps(config, indent=2) + "\n")
257
+ for filename in ("tokenizer.json", "tokenizer_config.json", "chat_template.jinja", "generation_config.json",
258
+ "preprocessor_config.json", "video_preprocessor_config.json"):
259
+ if (source / filename).is_file():
260
+ shutil.copy2(source / filename, output / filename)
261
+ files = {path.name: {"size": path.stat().st_size, "sha256": sha256(path)}
262
+ for path in sorted(output.iterdir()) if path.is_file()}
263
+ manifest = {"device": "cpu", "quantization": quantization, "vision": "source BF16, unquantized",
264
+ "mtp": "excluded from target; original sidecar retained in source", "source_files": source_records,
265
+ "sanitizer_revision": SANITIZER_REV, "sanitizer_sha256": SANITIZER_SHA,
266
+ "row_chunk": row_chunk, "output_files": files, "transforms": transforms,
267
+ "elapsed_s": time.monotonic() - started, "inference_qualified": False}
268
+ (output / "conversion-manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
269
+ return manifest
270
+
271
+
272
+ if __name__ == "__main__":
273
+ parser = argparse.ArgumentParser()
274
+ parser.add_argument("--source", type=Path, required=True)
275
+ parser.add_argument("--output", type=Path, required=True)
276
+ parser.add_argument("--expected", type=Path, required=True)
277
+ parser.add_argument("--row-chunk", type=int, default=128)
278
+ args = parser.parse_args()
279
+ result = convert(args.source, args.output, json.loads(args.expected.read_text()), row_chunk=args.row_chunk)
280
+ print(json.dumps({key: result[key] for key in ["device", "elapsed_s", "inference_qualified"]}, indent=2))
pyproject.toml ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "mlx-agent-tools"
7
+ version = "1.0.0"
8
+ description = "Reusable acceleration, quantization, conversion, and serving utilities for Apple Silicon AI agents."
9
+ readme = "README.md"
10
+ license = {text = "MIT"}
11
+ authors = [
12
+ {name = "Chengyi Xu", email = "wilson_xu@hiklik.ai"},
13
+ {name = "Nexora"}
14
+ ]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Operating System :: MacOS",
19
+ "Topic :: Scientific/Engineering :: Artificial Intelligence"
20
+ ]
21
+ requires-python = ">=3.10"
22
+ dependencies = [
23
+ "mlx>=0.22.0",
24
+ "numpy>=1.24.0",
25
+ ]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/chengyixu/mlx-agent-tools"
29
+ Repository = "https://github.com/chengyixu/mlx-agent-tools"
tests/test_cpu_checkpoint.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Real bounded checkpoint access tests. No GPU or full-model load."""
2
+ import importlib.util
3
+ import json
4
+ from pathlib import Path
5
+ import tempfile
6
+ import unittest
7
+
8
+ import mlx.core as mx
9
+ mx.set_default_device(mx.cpu)
10
+
11
+ PATH = Path(__file__).resolve().parent.parent / "mlx_agent_tools" / "cpu_checkpoint.py"
12
+ SPEC = importlib.util.spec_from_file_location('cpu_checkpoint', PATH)
13
+ MODULE = None
14
+ if PATH.exists():
15
+ MODULE = importlib.util.module_from_spec(SPEC)
16
+ SPEC.loader.exec_module(MODULE)
17
+
18
+
19
+ class BoundedRowsContract(unittest.TestCase):
20
+ def helper(self):
21
+ self.assertIsNotNone(MODULE, 'Bounded CPU checkpoint access is not implemented')
22
+ return MODULE
23
+
24
+ def fixture(self, root):
25
+ # BF16 and packed U32 should survive exactly, with independent literal expectations.
26
+ mx.save_safetensors(root / 'model.safetensors', {
27
+ 'norm.weight': mx.array([0., .5, 1., 2.], dtype=mx.bfloat16),
28
+ 'packed.weight': mx.array([[1, 2], [3, 4], [5, 6]], dtype=mx.uint32)})
29
+ (root / 'model.safetensors.index.json').write_text(json.dumps({'weight_map': {
30
+ 'norm.weight': 'model.safetensors', 'packed.weight': 'model.safetensors'}}))
31
+
32
+ def test_partial_bf16_rows_preserve_values_without_float32_reinterpretation(self):
33
+ c = self.helper()
34
+ with tempfile.TemporaryDirectory() as temp:
35
+ root = Path(temp)
36
+ self.fixture(root)
37
+ result = c.rows(root, 'norm.weight', 1, 3)
38
+ self.assertEqual(result.dtype, mx.bfloat16)
39
+ self.assertEqual(result.tolist(), [.5, 1.])
40
+
41
+ def test_packed_u32_rows_are_not_cast_to_signed_or_float(self):
42
+ c = self.helper()
43
+ with tempfile.TemporaryDirectory() as temp:
44
+ root = Path(temp)
45
+ self.fixture(root)
46
+ result = c.rows(root, 'packed.weight', 2, 3)
47
+ self.assertEqual(result.dtype, mx.uint32)
48
+ self.assertEqual(result.tolist(), [[5, 6]])
49
+
50
+ def test_bounds_and_memory_guard_reject_before_tensor_materialization(self):
51
+ c = self.helper()
52
+ with tempfile.TemporaryDirectory() as temp:
53
+ root = Path(temp)
54
+ self.fixture(root)
55
+ for start, end in [(-1, 1), (0, 4), (2, 1), (1, 1)]:
56
+ with self.subTest(start=start, end=end):
57
+ with self.assertRaisesRegex(ValueError, 'row'):
58
+ c.rows(root, 'packed.weight', start, end)
59
+ with self.assertRaisesRegex(ValueError, 'memory|bound'):
60
+ c.rows(root, 'packed.weight', 0, 3, max_bytes=8)
61
+
62
+ def test_index_path_escape_is_rejected(self):
63
+ c = self.helper()
64
+ with tempfile.TemporaryDirectory() as temp:
65
+ root = Path(temp)
66
+ self.fixture(root)
67
+ (root / 'model.safetensors.index.json').write_text(json.dumps({'weight_map': {
68
+ 'norm.weight': '../model.safetensors'}}))
69
+ with self.assertRaisesRegex(ValueError, 'path|shard'):
70
+ c.rows(root, 'norm.weight', 0, 1)
71
+
72
+ def test_missing_tensor_does_not_fabricate_zeros(self):
73
+ c = self.helper()
74
+ with tempfile.TemporaryDirectory() as temp:
75
+ root = Path(temp)
76
+ self.fixture(root)
77
+ with self.assertRaisesRegex(ValueError, 'tensor'):
78
+ c.rows(root, 'missing.weight', 0, 1)
79
+
80
+
81
+ if __name__ == '__main__':
82
+ unittest.main()
tests/test_inference_window.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exclusive-window lifecycle tests with real subprocess/lock-free controller double."""
2
+ import importlib.util
3
+ from pathlib import Path
4
+ import subprocess
5
+ import sys
6
+ import tempfile
7
+ import unittest
8
+ from contextlib import contextmanager
9
+ from types import SimpleNamespace
10
+
11
+ PATH = Path(__file__).resolve().parent.parent / "mlx_agent_tools" / "inference_window.py"
12
+ SPEC = importlib.util.spec_from_file_location('inference_window', PATH)
13
+ MODULE = None
14
+ if PATH.exists():
15
+ MODULE = importlib.util.module_from_spec(SPEC)
16
+ SPEC.loader.exec_module(MODULE)
17
+
18
+
19
+ class Controller:
20
+ def __init__(self, busy=False):
21
+ self.previous = SimpleNamespace(key='uncensored', kind='text', port=7871)
22
+ self.active = True
23
+ self.busy = busy
24
+ self.events = []
25
+
26
+ @contextmanager
27
+ def lock(self):
28
+ self.events.append('lock')
29
+ try:
30
+ yield
31
+ finally:
32
+ self.events.append('unlock')
33
+
34
+ def profiles(self): return {'uncensored': self.previous}
35
+ def occupied(self, port): return self.active if port == 7871 else False
36
+ def label(self, profile): return profile.key
37
+ def loaded(self, label): return self.active
38
+ def request_json(self, profile, path): return {'idle': not self.busy}
39
+ def text_snapshot_idle(self, snapshot): return snapshot.get('idle') is True
40
+ def validate_paths(self, profile): pass
41
+ def stop_all(self):
42
+ self.events.append('stop')
43
+ self.active = False
44
+ def start_locked(self, profile, quiet=False):
45
+ self.events.append('restore')
46
+ self.active = True
47
+ def status(self, profile): return {'api_ready': self.active}
48
+
49
+
50
+ class InferenceWindowContract(unittest.TestCase):
51
+ def helper(self):
52
+ self.assertIsNotNone(MODULE, 'Inference window runner is not implemented')
53
+ return MODULE
54
+
55
+ def test_restores_original_service_after_worker_failure(self):
56
+ module = self.helper()
57
+ controller = Controller()
58
+ with tempfile.TemporaryDirectory() as temp:
59
+ record = module.run_window([sys.executable, '-c', 'raise SystemExit(3)'],
60
+ Path(temp), timeout=10, controller=controller)
61
+ self.assertEqual(record['worker_returncode'], 3)
62
+ self.assertTrue(record['restored'])
63
+ self.assertEqual(controller.events, ['lock', 'stop', 'restore', 'unlock'])
64
+
65
+ def test_busy_engine_rejected_without_stop_or_child_launch(self):
66
+ module = self.helper()
67
+ controller = Controller(busy=True)
68
+ with tempfile.TemporaryDirectory() as temp:
69
+ marker = Path(temp) / 'child-ran'
70
+ with self.assertRaisesRegex(RuntimeError, 'busy'):
71
+ module.run_window([sys.executable, '-c', f'from pathlib import Path;Path({str(marker)!r}).touch()'],
72
+ Path(temp), timeout=10, controller=controller)
73
+ self.assertFalse(marker.exists())
74
+ self.assertNotIn('stop', controller.events)
75
+ self.assertNotIn('restore', controller.events)
76
+
77
+ def test_external_accelerator_job_is_not_interrupted_or_overlapped(self):
78
+ module = self.helper()
79
+ controller = Controller()
80
+ with tempfile.TemporaryDirectory() as temp:
81
+ marker = Path(temp) / 'child-ran'
82
+ with self.assertRaisesRegex(RuntimeError, 'accelerator|GPU'):
83
+ module.run_window([sys.executable, '-c', f'from pathlib import Path;Path({str(marker)!r}).touch()'],
84
+ Path(temp), timeout=10, controller=controller,
85
+ external_work=lambda: [{'pid': 123, 'kind': 'encoder_training'}])
86
+ self.assertFalse(marker.exists())
87
+ self.assertNotIn('stop', controller.events)
88
+ self.assertTrue(controller.active)
89
+
90
+ def test_small_idle_llama_can_remain_resident_without_being_stopped(self):
91
+ module = self.helper()
92
+ with tempfile.TemporaryDirectory() as temp:
93
+ weight = Path(temp) / 'small.gguf'
94
+ weight.write_bytes(b'GGUF')
95
+ argv = ['llama-server', '-m', str(weight), '--host', '127.0.0.1', '--port', '18773']
96
+ replies = {'/props': {'model_path': str(weight)},
97
+ '/slots': [{'n_ctx': 4096, 'is_processing': False}]}
98
+ self.assertTrue(module.small_idle_llama(argv, query=lambda port, path: replies[path]))
99
+ replies['/slots'][0]['is_processing'] = True
100
+ self.assertFalse(module.small_idle_llama(argv, query=lambda port, path: replies[path]))
101
+ replies['/slots'][0]['is_processing'] = False
102
+ replies['/props']['model_path'] = str(Path(temp) / 'other.gguf')
103
+ self.assertFalse(module.small_idle_llama(argv, query=lambda port, path: replies[path]))
104
+
105
+ def test_small_engine_unknown_activity_is_not_assumed_idle(self):
106
+ module = self.helper()
107
+ with tempfile.TemporaryDirectory() as temp:
108
+ weight = Path(temp) / 'small.gguf'
109
+ weight.write_bytes(b'GGUF')
110
+ argv = ['llama-server', '-m', str(weight), '--host', '127.0.0.1', '--port', '18773']
111
+ self.assertFalse(module.small_idle_llama(argv, query=lambda port, path: None))
112
+
113
+ def test_timeout_terminates_owned_child_and_restores_service(self):
114
+ module = self.helper()
115
+ controller = Controller()
116
+ with tempfile.TemporaryDirectory() as temp:
117
+ record = module.run_window([sys.executable, '-c', 'import time;time.sleep(60)'],
118
+ Path(temp), timeout=.2, controller=controller)
119
+ self.assertTrue(record['timed_out'])
120
+ self.assertTrue(record['restored'])
121
+ self.assertNotEqual(record['worker_returncode'], 0)
122
+ self.assertTrue(controller.active)
123
+
124
+
125
+ if __name__ == '__main__':
126
+ unittest.main()
tests/test_redacting_log.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import unittest
3
+ from mlx_agent_tools.redacting_log import SecretLogStream
4
+
5
+ class RedactingLogTests(unittest.TestCase):
6
+ def test_redacts_exact_secret(self):
7
+ sink = io.StringIO()
8
+ stream = SecretLogStream(sink, "sk-SUPER-SECRET-KEY-1234")
9
+ stream.write("Server started with key sk-SUPER-SECRET-KEY-1234 ok\n")
10
+ self.assertNotIn("sk-SUPER-SECRET-KEY-1234", sink.getvalue())
11
+ self.assertIn("[redacted]", sink.getvalue())
12
+
13
+ def test_accumulates_until_newline(self):
14
+ sink = io.StringIO()
15
+ stream = SecretLogStream(sink, "SECRET")
16
+ stream.write("part1: SEC")
17
+ self.assertEqual(sink.getvalue(), "")
18
+ stream.write("RET is hidden\n")
19
+ self.assertNotIn("SECRET", sink.getvalue())
20
+ self.assertIn("[redacted]", sink.getvalue())
21
+
22
+ def test_properties(self):
23
+ sink = io.StringIO()
24
+ stream = SecretLogStream(sink, "SECRET")
25
+ self.assertFalse(stream.isatty())
26
+ self.assertEqual(stream.encoding, "utf-8")
27
+ stream.flush()
28
+
29
+ if __name__ == "__main__":
30
+ unittest.main()
tests/test_separate_mtp.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Protect exact tensor bytes while separating already-normalized embedded MTP."""
2
+ import importlib.util,json,tempfile,unittest
3
+ from pathlib import Path
4
+ import mlx.core as mx
5
+ mx.set_default_device(mx.cpu)
6
+ path=Path(__file__).resolve().parent.parent / "mlx_agent_tools" / "separate_mtp.py";module=None
7
+ if path.exists():
8
+ spec=importlib.util.spec_from_file_location('separate_mtp',path);module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
9
+
10
+ class MTPPackaging(unittest.TestCase):
11
+ def helper(self):
12
+ self.assertIsNotNone(module,'MTP separation helper missing');return module
13
+ def fixture(self,root):
14
+ src=root/'source';src.mkdir();w={'language_model.model.norm.weight':mx.array([1.,2.],dtype=mx.bfloat16),'language_model.mtp.norm.weight':mx.array([2.,3.],dtype=mx.bfloat16),'language_model.mtp.fc.weight':mx.ones((2,4),dtype=mx.bfloat16)}
15
+ mx.save_safetensors(src/'model.safetensors',w,metadata={'format':'mlx'})
16
+ (src/'model.safetensors.index.json').write_text(json.dumps({'weight_map':{k:'model.safetensors' for k in w}}));(src/'config.json').write_text(json.dumps({'model_type':'qwen3_5'}));return src,w
17
+ def test_trunk_norm_and_head_payloads_preserved_without_an_extra_shift(self):
18
+ m=self.helper()
19
+ with tempfile.TemporaryDirectory() as t:
20
+ root=Path(t);src,w=self.fixture(root);dst=root/'prepared';m.prepare(src,dst)
21
+ index=json.loads((dst/'model.safetensors.index.json').read_text())['weight_map'];self.assertEqual(set(index),{'language_model.model.norm.weight'})
22
+ trunk=mx.load(dst/index['language_model.model.norm.weight']);head=mx.load(dst/'mtp.safetensors')
23
+ self.assertEqual(trunk['language_model.model.norm.weight'].tolist(),[1.,2.]);self.assertEqual(head['mtp.norm.weight'].tolist(),[2.,3.]);self.assertEqual(head['mtp.fc.weight'].tolist(),[[1.]*4]*2)
24
+ self.assertEqual(mx.load(src/'model.safetensors')['language_model.mtp.norm.weight'].tolist(),[2.,3.])
25
+ def test_existing_output_and_non_mtp_checkpoint_refused(self):
26
+ m=self.helper()
27
+ with tempfile.TemporaryDirectory() as t:
28
+ root=Path(t);src,w=self.fixture(root)
29
+ with self.assertRaisesRegex(ValueError,'exists|source'):m.prepare(src,src)
30
+ (src/'model.safetensors.index.json').write_text(json.dumps({'weight_map':{'language_model.model.norm.weight':'model.safetensors'}}))
31
+ with self.assertRaisesRegex(ValueError,'MTP|index'):m.prepare(src,root/'out')
32
+
33
+ if __name__=='__main__':unittest.main()
tests/test_stream_convert.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CPU-only conversion boundary tests; no production model is instantiated."""
2
+ import hashlib
3
+ import importlib.util
4
+ import json
5
+ from pathlib import Path
6
+ import tempfile
7
+ import unittest
8
+
9
+ import mlx.core as mx
10
+ import numpy as np
11
+
12
+ mx.set_default_device(mx.cpu)
13
+ PATH = Path(__file__).resolve().parent.parent / "mlx_agent_tools" / "stream_convert.py"
14
+ SPEC = importlib.util.spec_from_file_location("stream_convert", PATH)
15
+ MODULE = importlib.util.module_from_spec(SPEC) if SPEC else None
16
+ if SPEC and SPEC.loader and Path(SPEC.origin).exists():
17
+ SPEC.loader.exec_module(MODULE)
18
+ else:
19
+ MODULE = None
20
+
21
+
22
+ class ConversionContract(unittest.TestCase):
23
+ def converter(self):
24
+ self.assertIsNotNone(MODULE, "The bounded CPU converter is not implemented")
25
+ return MODULE
26
+
27
+ def fixture(self, root, tensors):
28
+ source = root / "source"
29
+ source.mkdir()
30
+ config = {"model_type": "qwen3_5", "text_config": {"tie_word_embeddings": False,
31
+ "max_position_embeddings": 262144, "mtp_num_hidden_layers": 1},
32
+ "vision_config": {"in_channels": 3}}
33
+ (source / "config.json").write_text(json.dumps(config))
34
+ mx.save_safetensors(source / "model.safetensors", tensors, metadata={"format": "pt"})
35
+ (source / "model.safetensors.index.json").write_text(json.dumps({
36
+ "weight_map": {name: "model.safetensors" for name in tensors}}))
37
+ digest = hashlib.sha256((source / "model.safetensors").read_bytes()).hexdigest()
38
+ return source, {"model.safetensors": {"size": (source / "model.safetensors").stat().st_size,
39
+ "sha256": digest}}
40
+
41
+ def convert(self, source, hashes, output):
42
+ return self.converter().convert(source, output, hashes, row_chunk=2)
43
+
44
+ def load(self, output):
45
+ index = json.loads((output / "model.safetensors.index.json").read_text())
46
+ tensors = {}
47
+ for file in set(index["weight_map"].values()):
48
+ tensors.update(mx.load(output / file))
49
+ return tensors, index
50
+
51
+ def test_rows_quantize_real_linear_and_embedding_without_losing_rows(self):
52
+ c = self.converter()
53
+ with tempfile.TemporaryDirectory() as temp:
54
+ root = Path(temp)
55
+ w = mx.arange(5 * 64).reshape(5, 64).astype(mx.bfloat16) / 32
56
+ source, hashes = self.fixture(root, {
57
+ "model.language_model.layers.0.mlp.up_proj.weight": w,
58
+ "model.language_model.embed_tokens.weight": w})
59
+ out = root / "output"
60
+ self.convert(source, hashes, out)
61
+ tensors, index = self.load(out)
62
+ for name in ["language_model.model.layers.0.mlp.up_proj", "language_model.model.embed_tokens"]:
63
+ self.assertEqual(tensors[name + ".weight"].shape, (5, 8))
64
+ decoded = mx.dequantize(tensors[name + ".weight"], tensors[name + ".scales"],
65
+ tensors[name + ".biases"], group_size=64, bits=4)
66
+ self.assertLess(float(mx.max(mx.abs(decoded.astype(mx.float32) - w))), 0.14)
67
+ self.assertEqual(len(index["weight_map"]), 6)
68
+ self.assertEqual(json.loads((out / "config.json").read_text())["quantization"]["bits"], 4)
69
+
70
+ def test_source_norm_shift_conv_layout_and_vision_layout_use_pinned_sanitizer(self):
71
+ self.converter()
72
+ with tempfile.TemporaryDirectory() as temp:
73
+ root = Path(temp)
74
+ conv = mx.arange(3 * 1 * 4).reshape(3, 1, 4).astype(mx.bfloat16)
75
+ patch = mx.arange(2 * 3 * 2 * 2 * 2).reshape(2, 3, 2, 2, 2).astype(mx.bfloat16)
76
+ source, hashes = self.fixture(root, {
77
+ "model.language_model.layers.0.input_layernorm.weight": mx.array([0., .5], dtype=mx.bfloat16),
78
+ "model.language_model.layers.0.linear_attn.conv1d.weight": conv,
79
+ "model.visual.patch_embed.proj.weight": patch,
80
+ "model.visual.blocks.0.attn.qkv.weight": mx.ones((3, 64), dtype=mx.bfloat16),
81
+ "model.language_model.layers.0.linear_attn.A_log": mx.array([1., 2.], dtype=mx.float32)})
82
+ out = root / "output"
83
+ self.convert(source, hashes, out)
84
+ t, _ = self.load(out)
85
+ self.assertEqual(t["language_model.model.layers.0.input_layernorm.weight"].tolist(), [1., 1.5])
86
+ self.assertEqual(t["language_model.model.layers.0.linear_attn.conv1d.weight"].shape, (3, 4, 1))
87
+ self.assertEqual(t["vision_tower.patch_embed.proj.weight"].shape, (2, 2, 2, 2, 3))
88
+ self.assertEqual(t["vision_tower.patch_embed.proj.weight"].reshape(-1).tolist(),
89
+ patch.transpose(0, 2, 3, 4, 1).reshape(-1).tolist())
90
+ self.assertNotIn("vision_tower.blocks.0.attn.qkv.scales", t)
91
+ self.assertEqual(t["language_model.model.layers.0.linear_attn.A_log"].dtype, mx.float32)
92
+
93
+ def test_mtp_is_preserved_in_source_but_not_mixed_into_target(self):
94
+ self.converter()
95
+ with tempfile.TemporaryDirectory() as temp:
96
+ root = Path(temp)
97
+ source, hashes = self.fixture(root, {
98
+ "lm_head.weight": mx.ones((2, 64), dtype=mx.bfloat16),
99
+ "mtp.fc.weight": mx.ones((2, 128), dtype=mx.bfloat16)})
100
+ out = root / "output"
101
+ self.convert(source, hashes, out)
102
+ t, _ = self.load(out)
103
+ self.assertTrue(all(not name.startswith("mtp.") for name in t))
104
+ self.assertEqual(len(mx.load(source / "model.safetensors")), 2)
105
+
106
+ def test_bad_hash_same_size_never_produces_a_qualified_output(self):
107
+ self.converter()
108
+ with tempfile.TemporaryDirectory() as temp:
109
+ root = Path(temp)
110
+ source, hashes = self.fixture(root, {"lm_head.weight": mx.ones((2, 64), dtype=mx.bfloat16)})
111
+ hashes["model.safetensors"]["sha256"] = "0" * 64
112
+ out = root / "output"
113
+ with self.assertRaisesRegex(ValueError, "SHA|hash"):
114
+ self.convert(source, hashes, out)
115
+ self.assertFalse((out / "conversion-manifest.json").exists())
116
+
117
+ def test_nonfinite_unknown_weight_and_unsafe_destination_fail_closed(self):
118
+ c = self.converter()
119
+ for name, w, message in [
120
+ ("lm_head.weight", mx.full((2, 64), float("nan")), "finite"),
121
+ ("model.language_model.mystery.weight", mx.ones((2, 64)), "unsupported|unknown")]:
122
+ with self.subTest(name=name), tempfile.TemporaryDirectory() as temp:
123
+ root = Path(temp)
124
+ source, hashes = self.fixture(root, {name: w})
125
+ with self.assertRaisesRegex(ValueError, message):
126
+ self.convert(source, hashes, root / "output")
127
+ self.assertFalse((root / "output/conversion-manifest.json").exists())
128
+ with tempfile.TemporaryDirectory() as temp:
129
+ source, hashes = self.fixture(Path(temp), {"lm_head.weight": mx.ones((2, 64))})
130
+ with self.assertRaisesRegex(ValueError, "destination|source|exists"):
131
+ self.convert(source, hashes, source)
132
+
133
+ def test_multishard_index_is_complete_and_converted_norms_are_idempotent(self):
134
+ c = self.converter()
135
+ with tempfile.TemporaryDirectory() as temp:
136
+ root = Path(temp)
137
+ source, hashes = self.fixture(root, {
138
+ "lm_head.weight": mx.ones((3, 64), dtype=mx.bfloat16),
139
+ "model.language_model.layers.0.input_layernorm.weight": mx.array([0., .5], dtype=mx.bfloat16),
140
+ "model.language_model.layers.0.mlp.up_proj.weight": mx.ones((5, 64), dtype=mx.bfloat16)})
141
+ out = root / "output"
142
+ c.convert(source, out, hashes, row_chunk=2, shard_bytes=100)
143
+ tensors, index = self.load(out)
144
+ self.assertGreater(len(set(index["weight_map"].values())), 1)
145
+ self.assertEqual(len(tensors), 7)
146
+ from types import SimpleNamespace
147
+ owner = SimpleNamespace(config=SimpleNamespace(
148
+ text_config=SimpleNamespace(tie_word_embeddings=False),
149
+ vision_config=SimpleNamespace(in_channels=3)))
150
+ again = c.sanitizer()(owner, tensors)
151
+ self.assertEqual(again["language_model.model.layers.0.input_layernorm.weight"].tolist(), [1., 1.5])
152
+ self.assertEqual(set(again), set(tensors))
153
+
154
+ def test_duplicate_index_shard_members_fail_before_output(self):
155
+ self.converter()
156
+ with tempfile.TemporaryDirectory() as temp:
157
+ root = Path(temp)
158
+ source, hashes = self.fixture(root, {"lm_head.weight": mx.ones((2, 64), dtype=mx.bfloat16)})
159
+ (source / "model.safetensors.index.json").write_text(json.dumps({"weight_map": {
160
+ "not_lm_head.weight": "model.safetensors"}}))
161
+ with self.assertRaisesRegex(ValueError, "Index/header"):
162
+ self.convert(source, hashes, root / "output")
163
+ self.assertFalse((root / "output").exists())
164
+
165
+ def test_manifest_full_output_hashes_and_index_payload_size_are_independent(self):
166
+ self.converter()
167
+ with tempfile.TemporaryDirectory() as temp:
168
+ root = Path(temp)
169
+ source, hashes = self.fixture(root, {"lm_head.weight": mx.ones((3, 64), dtype=mx.bfloat16)})
170
+ out = root / "output"
171
+ self.convert(source, hashes, out)
172
+ manifest = json.loads((out / "conversion-manifest.json").read_text())
173
+ t, index = self.load(out)
174
+ self.assertEqual(index["metadata"]["total_size"], sum(v.nbytes for v in t.values()))
175
+ for name, record in manifest["output_files"].items():
176
+ self.assertEqual(hashlib.sha256((out / name).read_bytes()).hexdigest(), record["sha256"])
177
+ self.assertEqual(manifest["device"], "cpu")
178
+
179
+
180
+ if __name__ == "__main__":
181
+ unittest.main()