Emily.Quantization.Transform (emily v1.4.0)

Copy Markdown View Source

Quantize the dense layers of an Axon model, graph and parameters together, so a stock Axon or Bumblebee model runs its matmuls through MLX's group-wise quantized kernels.

Every :dense node is rewritten to a :quantized_dense node that calls Emily.Quantization.Layers.quantized_dense/4, and every dense kernel in the Axon.ModelState is replaced with an %Emily.QuantizedWeight{}. Biases stay as float tensors. The approach mirrors Axon.Quantization, but targets MLX quantization via Emily.QuantizedWeight.

Optional dependency

This module depends on :axon, which is declared optional: true in Emily's mix.exs. Consumers who don't pull Axon into their own project get a clean build: the module definition is wrapped in Code.ensure_loaded?/1 and elides entirely when Axon is missing. To use it, add Axon to your own deps/0 (Bumblebee already depends on it):

{:axon, "~> 0.8"}

Usage

quantize/3 takes the model and its parameters and returns both rewritten:

{:ok, %{model: model, params: params} = model_info} =
  Bumblebee.load_model({:hf, "Qwen/Qwen3-0.6B"})

{qmodel, qparams} =
  Emily.Quantization.Transform.quantize(model, params, bits: 4, group_size: 64)

qmodel_info = %{model_info | model: qmodel, params: qparams}

The quantized weights are evaluated before quantize/3 returns, so they no longer depend on the dense kernels they came from. Once the caller drops its reference to the original parameters (params above), the dense kernels are freed and resident memory falls to the quantized size.

A small model end to end:

iex> model =
...>   Axon.input("features", shape: {nil, 64})
...>   |> Axon.dense(32, name: "fc")
iex> {init_fn, _predict_fn} = Axon.build(model)
iex> params = init_fn.(Nx.template({1, 64}, :f32), Axon.ModelState.empty())
iex> {qmodel, qparams} =
...>   Emily.Quantization.Transform.quantize(model, params, bits: 4, group_size: 64)
iex> Axon.properties(qmodel)["fc"]
:quantized_dense
iex> %Emily.QuantizedWeight{bits: 4, group_size: 64} = qparams.data["fc"]["kernel"]
iex> {_init_fn, predict_fn} = Axon.build(qmodel)
iex> predict_fn.(qparams, Nx.iota({2, 64}, type: :f32)) |> Nx.shape()
{2, 32}

Options

quantize/3, quantize_dense_layers/2 and quantize_model_state/3 accept the same options:

  • :bits — one of [1, 2, 3, 4, 6, 8]. Default 4.
  • :group_size — elements per quantization group. Default 128.
  • :transpose — default true. Groups run along the reduction axis: each [in, out] kernel is transposed to [out, in] before quantizing, which is the accuracy convention AWQ uses for LLM weights. Set false to keep the kernel's stored layout.
  • :mode — default "affine". One of "mxfp4", "mxfp8", or "nvfp4" selects MLX's microscaled modes. mxfp4 and nvfp4 use FP4-E2M1 lanes; mxfp8 uses FP8-E4M3 lanes. mxfp4 and mxfp8 use FP8-E8M0 per-group scales (group_size = 32); nvfp4 uses FP8-E4M3 per-group scales (group_size = 16, finer-grained per the NVIDIA convention).
  • :except — list of layer-name substrings. Dense layers whose name contains any of them stay as float :dense layers. Default []. When calling quantize_dense_layers/2 and quantize_model_state/3 separately, pass the same list to both.

Why not a defn-native from_dense

Axon's param initializers run inside an Nx.Defn.jit trace, but Emily.QuantizedWeight.from_dense/2 calls a NIF. So the rewriter keeps Axon.dense's float kernel parameter and quantize_model_state/3 swaps them for %QuantizedWeight{} after init — the same pattern Axon.Quantization.quantize_model_state/2 uses.

Summary

Types

An Axon.ModelState struct (Axon defines no type for it).

Functions

Rewrite the model graph and quantize its model state in one call.

Rewrite every :dense node in model into a :quantized_dense node that dispatches through Emily.Quantization.Layers.quantized_dense/4.

Walk model_state and replace each :dense layer's kernel tensor with an Emily.QuantizedWeight container. bias is left as a float tensor.

Types

model_state()

@type model_state() :: %Axon.ModelState{
  data: term(),
  frozen_parameters: term(),
  parameters: term(),
  state: term()
}

An Axon.ModelState struct (Axon defines no type for it).

Functions

quantize(model, model_state, opts \\ [])

@spec quantize(Axon.t(), model_state(), keyword()) :: {Axon.t(), model_state()}

Rewrite the model graph and quantize its model state in one call.

Equivalent to calling quantize_dense_layers/2 and quantize_model_state/3 with the same options. See the moduledoc for the options.

quantize_dense_layers(model, opts \\ [])

@spec quantize_dense_layers(
  Axon.t(),
  keyword()
) :: Axon.t()

Rewrite every :dense node in model into a :quantized_dense node that dispatches through Emily.Quantization.Layers.quantized_dense/4.

Only the node's op changes. Its parameters, mixed-precision policy, hooks and mode carry over. The rewritten model needs a state whose kernels are already %QuantizedWeight{}: initialize or load the original model's state and pass it through quantize_model_state/3, or supply a pre-quantized state. Axon's init_fn for the rewritten model runs the layers it initializes, so it cannot build that state itself.

Layer names are preserved, including generated ones such as "dense_0", so an existing float Axon.ModelState's keys still line up after quantization.

iex> model =
...>   Axon.input("features", shape: {nil, 64})
...>   |> Axon.dense(32, name: "fc")
...>   |> Axon.relu(name: "act")
iex> qmodel = Emily.Quantization.Transform.quantize_dense_layers(model)
iex> props = Axon.properties(qmodel)
iex> {props["fc"], props["act"]}
{:quantized_dense, :relu}

quantize_model_state(model, state, opts \\ [])

@spec quantize_model_state(Axon.t(), model_state(), keyword()) :: model_state()

Walk model_state and replace each :dense layer's kernel tensor with an Emily.QuantizedWeight container. bias is left as a float tensor.

model must be the original dense model (pre-rewrite): Axon.properties/1 is consulted to find the dense layer names. Mirrors Axon.Quantization.quantize_model_state/2.

Handles both :transpose conventions:

  • transpose: true (default) — transposes each kernel from [in, out] to [out, in] before quantizing, so groups align with the reduction axis (the AWQ-accuracy convention for LLM weights).
  • transpose: false — quantizes the kernel in place, [in, out] to packed [in, out_packed]. Groups run along out.

The quantized weights are evaluated before this function returns, a few layers at a time. MLX is lazy, so an unevaluated quantized weight keeps its dense source kernel alive as a pending input. With the weights evaluated, the dense kernels are freed as soon as the caller drops the original model_state.

iex> model =
...>   Axon.input("features", shape: {nil, 64})
...>   |> Axon.dense(128, name: "fc")
iex> {init_fn, _predict_fn} = Axon.build(model)
iex> params = init_fn.(Nx.template({1, 64}, :f32), Axon.ModelState.empty())
iex> qparams =
...>   Emily.Quantization.Transform.quantize_model_state(model, params,
...>     group_size: 64,
...>     transpose: false
...>   )
iex> qw = qparams.data["fc"]["kernel"]
iex> {qw.transpose, Nx.shape(qw.value)}
{false, {64, 16}}
iex> Nx.shape(qparams.data["fc"]["bias"])
{128}