|
| 1 | +# |
| 2 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | +# All rights reserved. |
| 4 | +# |
| 5 | +# This source code is licensed under the BSD-style license found in the |
| 6 | +# LICENSE file in the root directory of this source tree. |
| 7 | +# |
| 8 | + |
| 9 | +"""``mlx::gguf_linear``: linear layer against a GGUF-quantized weight. |
| 10 | +
|
| 11 | + out = x @ dequant(weight)^T (+ bias) |
| 12 | +
|
| 13 | +The weight is stored in the **exact GGUF packed block layout** (no repacking), |
| 14 | +so weights converted by llama.cpp / gguf-py can be consumed directly. The |
| 15 | +``format`` argument selects the GGUF quantization type. |
| 16 | +
|
| 17 | +This module is a thin **format router**: it owns the ``mlx::gguf_linear`` op |
| 18 | +identity (custom op, fake, and lowering registration) and dispatches on |
| 19 | +``format`` to a per-format implementation. Only ``"q6k"`` is supported today |
| 20 | +(see :mod:`.q6k.linear`); other formats raise ``NotImplementedError``. To add a |
| 21 | +format, implement ``eager_linear`` / ``emit_linear`` in a sibling package (e.g. |
| 22 | +``q4k``) and add a branch below. |
| 23 | +
|
| 24 | +Usage:: |
| 25 | +
|
| 26 | + import executorch.backends.mlx.custom_kernel_ops.gguf.linear # noqa: F401 |
| 27 | +
|
| 28 | + out = torch.ops.mlx.gguf_linear(x, weight, "q6k", bias) |
| 29 | + # x: (..., K) bf16 / fp16 / fp32 |
| 30 | + # weight: (N, (K/256)*210) uint8 GGUF q6_K blob |
| 31 | + # bias: (N,) or None activation dtype |
| 32 | + # out: (..., N) activation dtype |
| 33 | +""" |
| 34 | + |
| 35 | +from __future__ import annotations |
| 36 | + |
| 37 | +from typing import Optional |
| 38 | + |
| 39 | +import torch |
| 40 | +from torch import Tensor |
| 41 | +from torch.fx.node import Node |
| 42 | + |
| 43 | + |
| 44 | +# --------------------------------------------------------------------------- |
| 45 | +# Custom op + eager fallback (format-agnostic shell; dispatches by format) |
| 46 | +# --------------------------------------------------------------------------- |
| 47 | + |
| 48 | + |
| 49 | +@torch.library.custom_op("mlx::gguf_linear", mutates_args=()) |
| 50 | +def gguf_linear( |
| 51 | + x: Tensor, |
| 52 | + weight: Tensor, |
| 53 | + format: str, |
| 54 | + bias: Optional[Tensor] = None, |
| 55 | +) -> Tensor: |
| 56 | + """Linear against a GGUF-quantized weight. |
| 57 | +
|
| 58 | + Args: |
| 59 | + x: ``(..., K)`` activations (bf16 / fp16 / fp32). |
| 60 | + weight: ``(N, row_bytes)`` uint8 GGUF quant blob. |
| 61 | + format: GGUF quant type; only ``"q6k"`` supported. |
| 62 | + bias: optional ``(N,)`` of activation dtype. |
| 63 | +
|
| 64 | + Returns: |
| 65 | + ``(..., N)`` of activation dtype. |
| 66 | + """ |
| 67 | + if format == "q6k": |
| 68 | + from executorch.backends.mlx.custom_kernel_ops.gguf.q6k.linear import ( |
| 69 | + eager_linear, |
| 70 | + ) |
| 71 | + |
| 72 | + return eager_linear(x, weight, bias) |
| 73 | + raise NotImplementedError( |
| 74 | + f"mlx::gguf_linear: unsupported format {format!r}; only 'q6k' is supported" |
| 75 | + ) |
| 76 | + |
| 77 | + |
| 78 | +@torch.library.register_fake("mlx::gguf_linear") |
| 79 | +def gguf_linear_fake( |
| 80 | + x: Tensor, |
| 81 | + weight: Tensor, |
| 82 | + format: str, |
| 83 | + bias: Optional[Tensor] = None, |
| 84 | +) -> Tensor: |
| 85 | + N = weight.shape[0] |
| 86 | + out_shape = list(x.shape) |
| 87 | + out_shape[-1] = N |
| 88 | + return x.new_empty(out_shape, dtype=x.dtype) |
| 89 | + |
| 90 | + |
| 91 | +# --------------------------------------------------------------------------- |
| 92 | +# MLX handler (format router) |
| 93 | +# --------------------------------------------------------------------------- |
| 94 | + |
| 95 | +from executorch.backends.mlx.builder.op_registry import REGISTRY |
| 96 | +from executorch.backends.mlx.builder.program_builder import MLXProgramBuilder |
| 97 | +from executorch.backends.mlx.builder.slot_manager import Slot |
| 98 | + |
| 99 | + |
| 100 | +@REGISTRY.register(target=[torch.ops.mlx.gguf_linear.default]) |
| 101 | +def _gguf_linear_handler(P: MLXProgramBuilder, n: Node) -> Slot: |
| 102 | + """Route ``mlx::gguf_linear`` lowering to the per-format implementation.""" |
| 103 | + args = P.args(n) |
| 104 | + fmt = args[2] if len(args) >= 3 else None |
| 105 | + if fmt == "q6k": |
| 106 | + from executorch.backends.mlx.custom_kernel_ops.gguf.q6k.linear import ( |
| 107 | + emit_linear, |
| 108 | + ) |
| 109 | + |
| 110 | + return emit_linear(P, n) |
| 111 | + raise NotImplementedError( |
| 112 | + f"mlx::gguf_linear: unsupported format {fmt!r}; only 'q6k' is supported" |
| 113 | + ) |
0 commit comments