Skip to content
Open
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
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions examples/models/muse-glimmer/source_transformations/cuda.py
Original file line number Diff line number Diff line change
Expand Up @@ -870,11 +870,14 @@ def replace_8da4w_weights_for_cuda(model: nn.Module) -> None:
The shared 8da4w transform hands every linear its unquantized BF16 input
and its codes packed once into the kernels' layout: ``q4_zpf16_a8_linear``
quantizes the input per token with ``triton::int8_act_quant`` (the
reference formula, bitwise) and routes by M. The token embedding runs
``triton::q4_zpf16_embedding``.
Norm gains and runtime constants stay FP32.
reference formula, bitwise) and routes by M. Each fused gate/up MLP runs
``q4_zpf16_a8_gated_linear`` and the token embedding
``triton::q4_zpf16_embedding``. Norm gains and runtime constants stay FP32.
"""
from executorch.backends.cuda.q4_zpf16_a8_linear import q4_zpf16_a8_linear
from executorch.backends.cuda.q4_zpf16_a8_linear import (
q4_zpf16_a8_gated_linear,
q4_zpf16_a8_linear,
)
from executorch.backends.cuda.triton.kernels.q4_zpf16_a8_quantized_gemm import (
pack_q4_zpf16_linear,
)
Expand All @@ -891,6 +894,7 @@ def replace_8da4w_weights_for_cuda(model: nn.Module) -> None:
quantize_activations=False,
pack_codes=pack_q4_zpf16_linear,
packed_embedding=q4_zpf16_embedding,
packed_gated_linear=q4_zpf16_a8_gated_linear,
)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
BF16 activations, unsigned codes, FP16 scales, and fractional FP16 offsets. An
operator with integer kernels can take the activations before quantization and
quantize them itself with quantize_per_token_int8, read the codes in its own
layout, and serve the embedding too.
layout, and serve the embedding and the fused SwiGLU gate/up projection too.

The default linear uses FP32 reconstructed weights and rounds the result to
BF16. The eager checkpoint rounds each weight to BF16 before the dot product.
Expand Down Expand Up @@ -113,13 +113,31 @@ def forward(self, ids):
return self.packed_embedding(ids, self.codes, self.scale, self.offset)


class _PackedGatedMLP(nn.Module):
def __init__(self, mlp, packed_gated_linear):
super().__init__()
self.norm = mlp.norm
self.gate_up_proj = mlp.gate_up_proj
self.down_proj = mlp.down_proj
self.packed_gated_linear = packed_gated_linear

def forward(self, x):
gate_up = self.gate_up_proj
return self.down_proj(
self.packed_gated_linear(
self.norm(x), gate_up.codes, gate_up.scale, gate_up.offset
)
)


def replace_8da4w_weights(
model: nn.Module,
*,
packed_linear=None,
quantize_activations: bool = True,
pack_codes=None,
packed_embedding=None,
packed_gated_linear=None,
) -> None:
"""Replace decoder weights for export, preserving FP32 RMSNorm gains.

Expand All @@ -135,7 +153,10 @@ def replace_8da4w_weights(
Optional hooks for such an operator: pack_codes(codes) rewrites each
linear's codes once, at replacement, into the layout packed_linear reads;
packed_embedding(ids, codes, scale, offset) returns the BF16 embedding rows
from the canonical codes.
from the canonical codes; packed_gated_linear(x, codes, scale, offset)
takes a fused [gate; up] MLP projection's unquantized input and buffers
(codes as rewritten by pack_codes) and returns silu(gate) * up in BF16,
which replaces the MLP's gate/up linear and gating.

With pack_codes, and for packed_embedding, the weights are copies held as
frozen parameters, which AOTInductor does not clone for every compiled
Expand All @@ -149,6 +170,8 @@ def replace_8da4w_weights(
raise ValueError("quantize_activations=False requires packed_linear")
if packed_linear is None and pack_codes is not None:
raise ValueError("pack_codes requires packed_linear")
if packed_gated_linear is not None and quantize_activations:
raise ValueError("packed_gated_linear requires quantize_activations=False")

for name, child in list(model.named_modules()):
if isinstance(child, (nn.Linear, nn.Embedding)):
Expand All @@ -173,4 +196,16 @@ def replace_8da4w_weights(
model.set_submodule(name, replacement)
elif isinstance(child, RMSNorm):
model.set_submodule(name, _Norm(child, pack_codes is not None))
if packed_gated_linear is not None:
_replace_gated_mlps(model, packed_gated_linear)
model.requires_grad_(False)


def _replace_gated_mlps(model, packed_gated_linear):
from executorch.examples.models.muse_glimmer.model.model import MuseGlimmerMLP

for name, child in list(model.named_modules()):
if isinstance(child, MuseGlimmerMLP):
if not child.fuse_gate_up:
raise ValueError(f"packed_gated_linear needs a fused {name}")
model.set_submodule(name, _PackedGatedMLP(child, packed_gated_linear))
43 changes: 37 additions & 6 deletions examples/models/muse-glimmer/tests/test_torchao_8da4w.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,9 @@ def integer_linear(raw, codes, scale, offset):
)

def test_backend_hooks(self):
"""pack_codes rewrites linear codes once; the embedding gets its own
hook with the canonical buffers."""
"""pack_codes rewrites linear codes once; the embedding and the fused
gate/up MLP get their own hooks with the canonical buffers and the
unquantized MLP input."""
from executorch.examples.models.muse_glimmer.model.model import (
MuseGlimmerConfig,
MuseGlimmerMLP,
Expand Down Expand Up @@ -220,6 +221,10 @@ def packed_linear(x, codes, scale, offset):
calls.append(("linear", x, codes))
return x.new_zeros(*x.shape[:-1], codes.shape[0])

def packed_gated_linear(x, codes, scale, offset):
calls.append(("gated", x, codes, scale, offset))
return x.new_zeros(*x.shape[:-1], codes.shape[0] // 2)

def packed_embedding(ids, codes, scale, offset):
calls.append(("embedding", ids, codes, scale, offset))
return torch.zeros(*ids.shape, K, dtype=torch.bfloat16)
Expand All @@ -230,16 +235,19 @@ def packed_embedding(ids, codes, scale, offset):
quantize_activations=False,
pack_codes=pack_codes,
packed_embedding=packed_embedding,
packed_gated_linear=packed_gated_linear,
)
self.assertEqual(len(packed), 2)
x = _activations()
model["mlp"](x)
ids = torch.tensor([[1, 7]])
model["embed"](ids)
gate_up, down, embed = calls
self.assertEqual(gate_up[0], "linear")
self.assertTrue(torch.equal(gate_up[1], model["mlp"].norm(x)))
self.assertTrue(torch.equal(gate_up[2], weights["gate_up_proj"].codes ^ 0xFF))
gated, down, embed = calls
self.assertEqual(gated[0], "gated")
self.assertTrue(torch.equal(gated[1], model["mlp"].norm(x)))
self.assertTrue(torch.equal(gated[2], weights["gate_up_proj"].codes ^ 0xFF))
self.assertTrue(torch.equal(gated[3], weights["gate_up_proj"].scale))
self.assertTrue(torch.equal(gated[4], weights["gate_up_proj"].offset))
self.assertEqual(down[0], "linear")
self.assertTrue(torch.equal(down[2], weights["down_proj"].codes ^ 0xFF))
self.assertEqual(embed[0], "embedding")
Expand Down Expand Up @@ -298,6 +306,29 @@ def test_weights_without_pack_codes_are_checkpoint_buffers(self):
def test_hook_misuse_raises(self):
with self.assertRaisesRegex(ValueError, "pack_codes requires packed_linear"):
replace_8da4w_weights(_model(_weight()), pack_codes=lambda c: c)
with self.assertRaisesRegex(ValueError, "quantize_activations=False"):
replace_8da4w_weights(
_model(_weight()),
packed_linear=lambda *a: a[0],
packed_gated_linear=lambda *a: a[0],
)

def test_packed_gated_linear_needs_a_fused_mlp(self):
from executorch.examples.models.muse_glimmer.model.model import (
MuseGlimmerConfig,
MuseGlimmerMLP,
)

mlp = MuseGlimmerMLP(MuseGlimmerConfig(dim=K, fuse_gate_up=False))
for name in ("gate_proj", "up_proj", "down_proj"):
getattr(mlp, name).weight = nn.Parameter(_weight(), requires_grad=False)
with self.assertRaisesRegex(ValueError, "packed_gated_linear needs a fused"):
replace_8da4w_weights(
nn.ModuleDict({"mlp": mlp}),
packed_linear=lambda *a: a[0],
quantize_activations=False,
packed_gated_linear=lambda *a: a[0],
)

def test_quantize_activations_requires_packed_linear(self):
with self.assertRaisesRegex(ValueError, "requires packed_linear"):
Expand Down
106 changes: 73 additions & 33 deletions examples/models/muse-glimmer/tests/test_torchao_8da4w_cuda.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from unittest.mock import patch

import torch
import torch.nn.functional as F
from executorch.examples.models.muse_glimmer._quantize_ptq import _pack
from executorch.examples.models.muse_glimmer.export import common
from executorch.examples.models.muse_glimmer.export.export_solo import (
Expand Down Expand Up @@ -66,8 +67,8 @@
global_attn_cfg="[16,16,16,0]",
max_seq_len=64,
)
# qkv_proj, o_proj, gate_up_proj and down_proj per layer, and the lm_head.
LINEARS = 4 * CONFIG.n_layers + 1
# qkv_proj, o_proj and down_proj per layer, and the lm_head.
LINEARS = 3 * CONFIG.n_layers + 1
MAX_STEP = 16
TOKENS = torch.randint(
0, CONFIG.vocab_size, (1, 13), generator=torch.Generator().manual_seed(3)
Expand Down Expand Up @@ -127,6 +128,15 @@ def exact_linear(x, codes, scale, offset):
return exact_w4a8(x, unpack(codes), scale, offset)[0].bfloat16()


def silu_mul(y):
half = y.shape[-1] // 2
return F.silu(y[..., :half]) * y[..., half:]


def exact_gated_linear(x, codes, scale, offset):
return silu_mul(exact_linear(x, codes, scale, offset))


def bf16_linear(x, codes, scale, offset):
"""The eager reference tensors' math: the quantize-dequantized activation
and the reconstructed weight rounded to BF16, one rounding of their
Expand All @@ -139,6 +149,10 @@ def bf16_linear(x, codes, scale, offset):
return (a @ w.flatten(-2).bfloat16().double().T).bfloat16()


def bf16_gated_linear(x, codes, scale, offset):
return silu_mul(bf16_linear(x, codes, scale, offset))


def relative_error(actual, expected):
return float((actual.float() - expected.float()).norm() / expected.float().norm())

Expand Down Expand Up @@ -168,21 +182,24 @@ def setUp(self):
same checkpoint through the shared transform with the exact integer
W4A8 math, and with the reference tensors' BF16 math."""
self.reference = self.load().cuda()
self.exact = self.load(exact_linear).cuda()
self.exact = self.load(exact_linear, exact_gated_linear).cuda()
self.expected = {
name: self.logits(model)
for name, model in (
("reference", self.reference),
("exact", self.exact),
("bf16", self.load(bf16_linear).cuda()),
("bf16", self.load(bf16_linear, bf16_gated_linear).cuda()),
)
}

def load(self, linear=None):
def load(self, linear=None, gated_linear=None):
model, _ = load_torchao_model(self.ckpt, max_seq_len=CONFIG.max_seq_len)
if linear is not None:
replace_8da4w_weights(
model, packed_linear=linear, quantize_activations=False
model,
packed_linear=linear,
quantize_activations=False,
packed_gated_linear=gated_linear,
)
return model

Expand Down Expand Up @@ -233,33 +250,55 @@ def test_linears_on_real_inputs(self):
int8_act_quant,
)

records = []
linear = q4_zpf16_a8_linear_module.q4_zpf16_a8_linear
inputs = {"linear": [], "gated": []}

def record(x, qdata, scale, offset):
y = linear(x, qdata, scale, offset)
records.append((x, qdata, scale, offset, y))
return y
def recording(kind, op):
def record(x, qdata, scale, offset):
y = op(x, qdata, scale, offset)
inputs[kind].append((x, qdata, scale, offset, y))
return y

with patch.object(q4_zpf16_a8_linear_module, "q4_zpf16_a8_linear", record):
return record

with (
patch.object(
q4_zpf16_a8_linear_module,
"q4_zpf16_a8_linear",
recording("linear", q4_zpf16_a8_linear_module.q4_zpf16_a8_linear),
),
patch.object(
q4_zpf16_a8_linear_module,
"q4_zpf16_a8_gated_linear",
recording("gated", q4_zpf16_a8_linear_module.q4_zpf16_a8_gated_linear),
),
):
model = self.cuda_model()
with torch.no_grad():
model(TOKENS[:, :12].cuda(), torch.arange(12, device="cuda"))
self.assertEqual(len(records), LINEARS)
for x, qdata, scale, offset, y in records:
self.assertEqual(x.dtype, torch.bfloat16)
flat = x.reshape(-1, x.shape[-1])
codes, a_scale, _ = int8_act_quant(flat, x.shape[-1] // scale.shape[1])
expected_codes, expected_scale = quantize_per_token_int8(flat)
self.assertTrue(torch.equal(codes, expected_codes.to(torch.int8)))
self.assertTrue(torch.equal(a_scale, expected_scale.half().squeeze(-1)))
exact, residual = exact_w4a8(
flat, unpack_kernel_layout(qdata), scale, offset
)
bound = exact.abs() * 2**-8 + residual * 2**-21
bound += exact.abs().amax(0, keepdim=True) * 2**-16
error = (y.reshape(exact.shape).double() - exact).abs()
self.assertTrue(bool((error <= bound).all()))
self.assertEqual(len(inputs["linear"]), LINEARS)
self.assertEqual(len(inputs["gated"]), CONFIG.n_layers)
for kind, records in inputs.items():
for x, qdata, scale, offset, y in records:
self.assertEqual(x.dtype, torch.bfloat16)
flat = x.reshape(-1, x.shape[-1])
codes, a_scale, _ = int8_act_quant(flat, x.shape[-1] // scale.shape[1])
expected_codes, expected_scale = quantize_per_token_int8(flat)
self.assertTrue(torch.equal(codes, expected_codes.to(torch.int8)))
self.assertTrue(torch.equal(a_scale, expected_scale.half().squeeze(-1)))
exact, residual = exact_w4a8(
flat, unpack_kernel_layout(qdata), scale, offset
)
if kind == "linear":
bound = exact.abs() * 2**-8 + residual * 2**-21
bound += exact.abs().amax(0, keepdim=True) * 2**-16
else:
# Gate and up are rounded to BF16 before the gating, as
# the unfused linear's output would be.
exact = silu_mul(exact.bfloat16().double())
bound = exact.abs() * 2**-6 + exact.abs().amax() * 2**-12
bound += residual.amax() * 2**-21
error = (y.reshape(exact.shape).double() - exact).abs()
self.assertTrue(bool((error <= bound).all()), kind)

def test_embedding_is_bitwise(self):
model = self.cuda_model()
Expand Down Expand Up @@ -384,11 +423,11 @@ def test_single_sequence_export(self):
)
self.assertTrue(os.path.exists(os.path.join(out, "model.pte")))
kernels = {
"forward_1": "q4_zpf16_a8_gemv",
"forward_4": "q4_zpf16_a8_gemm_m4",
"forward_others": "q4_zpf16_a8_gemm_m16",
"forward_1": ("q4_zpf16_a8_gemv", "q4_zpf16_a8_gate_up_gemv"),
"forward_4": ("q4_zpf16_a8_gemm_m4", "q4_zpf16_a8_gate_up_m4"),
"forward_others": ("q4_zpf16_a8_gemm_m16", "q4_zpf16_a8_gate_up_m16"),
}
for name, linear in kernels.items():
for name, (linear, gated) in kernels.items():
(lowered,) = get_lowered_submodules(
program.exported_program(name).graph_module
)
Expand All @@ -402,8 +441,9 @@ def test_single_sequence_export(self):
ops,
{
"q4_zpf16_embedding": 1,
"int8_act_quant": LINEARS,
"int8_act_quant": LINEARS + CONFIG.n_layers,
linear: LINEARS,
gated: CONFIG.n_layers,
},
name,
)
Expand Down
Loading