Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,9 @@ ipython_config.py
# install all needed dependencies.
#Pipfile.lock

# uv
uv.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

Expand Down
22 changes: 17 additions & 5 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,28 @@ Check if the model has weights in the
[follow instructions](https://huggingface.co/spaces/safetensors/convert) to
convert it.

After that, add the model file to the
After that, add a package for the model to the
[`mlx_lm/models`](https://github.com/ml-explore/mlx-lm/tree/main/mlx_lm/models)
directory. You can see other examples there. We recommend starting from a model
that is similar to the model you are porting.

Make sure the name of the new model file is the same as the `model_type` in the
`config.json`, for example
Name the package after the `model_type` in the `config.json`, for example
[starcoder2](https://huggingface.co/bigcode/starcoder2-7b/blob/main/config.json#L17).

To determine the model layer names, we suggest either:
If the `model_type` is not a valid lower-case package name, or the model only
differs from an existing one in its `model_type`, map the `model_type` to a
package in `MODEL_REMAPPING` in `mlx_lm/utils.py`.

A package has `__init__.py` (exporting `Model` and `ModelArgs`), `config.py`
(`ModelArgs`) and `model.py` (`Model`). Optionally, `layers.py` has the blocks,
`checkpoint.py` the `sanitize` that converts checkpoint weights, `kernels.py` the
Metal kernels only this model uses, and `processor.py` and `vision.py` the
processor and the vision encoder of a model that takes images. Reuse the shared
code in
[`mlx_lm/layers`](https://github.com/ml-explore/mlx-lm/tree/main/mlx_lm/layers)
and [`mlx_lm/kernels`](https://github.com/ml-explore/mlx-lm/tree/main/mlx_lm/kernels).

Name the modules as the checkpoint names its weights. To determine the model
layer names, we suggest either:

- Refer to the Transformers implementation if you are familiar with the
codebase.
Expand Down
14 changes: 6 additions & 8 deletions mlx_lm/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -2173,22 +2173,20 @@ def main():
prompt = prompt[test_prompt.index("<query>") :]

if args.image:
processor = load_processor(model, config)
processor = load_processor(config)
if processor is None:
raise ValueError(f"The model {model_path} does not take images.")
from PIL import Image

images = [np.asarray(Image.open(f).convert("RGB")) for f in args.image]
prompt, pixel_values = processor(prompt, images=images)
prompt, media_inputs = processor(prompt, images=images)
else:
pixel_values = None
media_inputs = {}
prompt = tokenizer.encode(prompt, add_special_tokens=not use_chat_template)

if pixel_values is not None:
input_embeddings = model.embed_inputs(
mx.array(prompt), pixel_values=pixel_values
)
# The prefill runs on another stream: compute the vision rows first.
if media_inputs:
input_embeddings = model.embed_inputs(mx.array(prompt), **media_inputs)
# The prefill runs on another stream: compute the media rows first.
mx.eval(input_embeddings)
else:
input_embeddings = None
Expand Down
21 changes: 1 addition & 20 deletions mlx_lm/kernels/__init__.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,3 @@
# Copyright © 2026 Apple Inc.

"""Fused Metal kernels, one kernel per file."""

from .expert_routing import expert_routing
from .norm_add_norm import norm_add_norm, pre_norm
from .post_expert_norm_combine import post_expert_norm_combine
from .qk_norm import qk_norm
from .qk_norm_rope import qk_norm_rope
from .rms_norm_sigmoid_gate import rms_norm_sigmoid_gate
from .sparse_mla import sparse_mla_attention

__all__ = [
"expert_routing",
"norm_add_norm",
"post_expert_norm_combine",
"pre_norm",
"qk_norm",
"qk_norm_rope",
"rms_norm_sigmoid_gate",
"sparse_mla_attention",
]
"""Fused Metal kernels that more than one model uses, one kernel per file."""
106 changes: 106 additions & 0 deletions mlx_lm/kernels/bitlinear.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
# Copyright © 2025 Apple Inc.

"""BitNet's ternary matmul Metal kernel."""

import mlx.core as mx

__all__ = [
"bitlinear_matmul",
"make_bitlinear_kernel",
]


def make_bitlinear_kernel():
"""
Custom Metal kernel that performs matrix multiplication directly on
packed weights and scales the output. This eliminates the need to
store unpacked weights in memory.
"""
source = """
constexpr int M = 4;
constexpr int BLOCK = 32;
uint tid = thread_position_in_grid.y;
uint in_offset = thread_position_in_grid.x;
uint batch_idx = tid / (out_features / 4);
uint row_idx = tid % (out_features / 4);
float sum[4] = {0.0};
for (uint i = in_offset * M; i < in_features; i += BLOCK * M) {
float v[M];
for (int j=0; j<M; j++) {
v[j] = x[batch_idx * in_features + i + j];
}
for (int j=0; j<M; j++) {
uint8_t w = packed_weights[row_idx * in_features + i + j];
sum[0] += v[j] * ((w & 3) - 1);
sum[1] += v[j] * (((w >> 2) & 3) - 1);
sum[2] += v[j] * (((w >> 4) & 3) - 1);
sum[3] += v[j] * (((w >> 6) & 3) - 1);
}
}
for (int j=0; j<4; j++) {
sum[j] = simd_sum(sum[j]);
}
// Apply weight scaling by diving them or multiplying them
if (in_offset == 0) {
float scale = invert_weight_scales ? 1 / weight_scale[0] : weight_scale[0];
for (int i=0; i<4; i++) {
out[batch_idx * out_features + row_idx + i * (out_features/4)] = static_cast<T>(sum[i] * scale);
}
}
"""

return mx.fast.metal_kernel(
name="bitlinear_matmul",
input_names=["x", "packed_weights", "weight_scale"],
output_names=["out"],
source=source,
)


_bitlinear_kernel = make_bitlinear_kernel()


def bitlinear_matmul(
x: mx.array,
packed_weights: mx.array,
weight_scale: mx.array,
*,
out_features: int,
invert_weight_scales: bool,
) -> mx.array:
"""x times the ternary weights, packed four to a byte."""
original_shape = x.shape
if len(original_shape) > 2:
x = x.reshape(-1, original_shape[-1])
total_batch_elements, in_features = x.shape

dtype = weight_scale.dtype
assert x.dtype == dtype, "Wrong type for input."
out = _bitlinear_kernel(
inputs=[
x,
packed_weights,
weight_scale,
],
template=[
("T", dtype),
("invert_weight_scales", invert_weight_scales),
("in_features", in_features),
("out_features", out_features),
],
grid=(32, total_batch_elements * out_features // 4, 1),
threadgroup=(32, 1, 1), # SIMD width is 32 threads
output_shapes=[(total_batch_elements, out_features)],
output_dtypes=[dtype],
)[0]

if len(original_shape) > 2:
out = out.reshape(*original_shape[:-1], out_features)
return out
6 changes: 6 additions & 0 deletions mlx_lm/kernels/_common.py → mlx_lm/kernels/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@

import mlx.core as mx

__all__ = [
"BLOCK_SUM_HEADER",
"row_threads",
"scalar",
]

# A sum over all threads of a threadgroup of TG threads.
BLOCK_SUM_HEADER = """
template <int TG>
Expand Down
6 changes: 5 additions & 1 deletion mlx_lm/kernels/expert_routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@

import mlx.core as mx

from ._common import scalar
from mlx_lm.kernels.common import scalar

__all__ = [
"expert_routing",
]

_ROUTING_SOURCE = """
constexpr int R = (E + 31) / 32;
Expand Down
Loading
Loading