Skip to content
Draft
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
3 changes: 2 additions & 1 deletion engine/include/strata/quant/act.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,10 @@ void quantize_q8_1_ref(const float* x, void* y, int64_t n);
void quantize_q8_K_ref(const float* x, void* y, int64_t n);
/// Q4_0 from floats, ggml's `quantize_row_q4_0_ref` (the `--mtp-q4` requantizer's output format).
void quantize_q4_0_ref(const float* x, void* y, int64_t n);
/// Q5_0, IQ4_NL, Q5_K and Q6_K from floats, ggml's reference row quantizers.
/// Q5_0, IQ4_NL, Q4_K, Q5_K and Q6_K from floats, ggml's reference row quantizers.
void quantize_q5_0_ref(const float* x, void* y, int64_t n);
void quantize_iq4_nl_ref(const float* x, void* y, int64_t n);
void quantize_q4_K_ref(const float* x, void* y, int64_t n);
void quantize_q5_K_ref(const float* x, void* y, int64_t n);
void quantize_q6_K_ref(const float* x, void* y, int64_t n);

Expand Down
3 changes: 2 additions & 1 deletion engine/metal/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,8 @@ endif()

if(STRATA_METAL_POLY AND BUILD_TESTING)
add_executable(poly_memory_test poly_tests/memory_test.cpp ${S}/core/conversation_memory.cpp)
target_include_directories(poly_memory_test PRIVATE ${STRATA_ROOT}/include)
target_include_directories(poly_memory_test PRIVATE ${STRATA_ROOT}/include ${_strata_ggml_root}/ggml/include ${_strata_ggml_root}/ggml/src)
target_link_libraries(poly_memory_test PRIVATE strata_quant ggml-base)
add_test(NAME poly_memory_test COMMAND poly_memory_test)
set_tests_properties(poly_memory_test PROPERTIES LABELS "metal;poly;cpu")
add_executable(poly_conversation_memory_test ${S}/core/conversation_memory_test.cpp ${S}/core/conversation_memory.cpp)
Expand Down
272 changes: 263 additions & 9 deletions engine/metal/poly_tests/defaults_test.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,40 @@
"""Check effective Metal defaults and overrides with generated GGUFs, not real weights."""
import math
import os
from pathlib import Path
import re
import struct
import subprocess
import sys
import tempfile

exe, directory = sys.argv[1:]
directory = Path(directory)


def run(model, *options, expected=None, error=None):
result = subprocess.run([exe, '--model', str(directory / model), '--tokens', '1,2,3,4,5',
def run(model, *options, expected=None, error=None, env=None):
model_path = Path(model)
if not model_path.is_absolute():
model_path = directory / model
result = subprocess.run([exe, '--model', str(model_path), '--tokens', '1,2,3,4,5',
'--max-new', '4', '--max-context', '128', '--prompt-batch', '32',
'--threads', '2', '--no-draft', *options],
capture_output=True, text=True, timeout=60)
capture_output=True, text=True, timeout=60, env=env)
if error:
assert result.returncode != 0 and error in result.stderr, result.stderr
assert result.returncode != 0 and error in result.stderr, (result.returncode, result.stderr)
else:
assert result.returncode == 0, result.stderr
assert f'Metal {expected}' in result.stderr, result.stderr
return result.stdout
if expected is not None:
assert f'Metal {expected}' in result.stderr, result.stderr
return result.stdout, result.stderr


for arch in ('lfm', 'qwen35moe', 'qwen35moe-fp16', 'gemma4', 'glm5-next', 'deepseek4'):
model = f'tiny-{arch}.gguf'
kv = 'q8_0' if arch == 'qwen35moe' else 'fp16'
expected = f'optimize=on memory=balanced kv={kv}'
default = run(model, expected=expected)
explicit = run(model, '--metal-optimize', '--metal-memory', 'balanced', '--kv', kv, expected=expected)
default, _ = run(model, expected=expected)
explicit, _ = run(model, '--metal-optimize', '--metal-memory', 'balanced', '--kv', kv, expected=expected)
assert default == explicit, (arch, default, explicit)

run('tiny-qwen35moe.gguf', '--no-metal-optimize', '--metal-memory', 'legacy', '--kv', 'fp16',
Expand All @@ -37,4 +46,249 @@ def run(model, *options, expected=None, error=None):
run('tiny-gemma4.gguf', '--kv', 'q8_0', error="this is a 'gemma4' model")
run('tiny-qwen35moe-fp16.gguf', '--kv', 'q8_0', error='multiple of 32')
run('tiny-lfm.gguf', '--metal-memory', 'invalid', error='requires legacy or balanced')
print('Metal defaults: effective settings, explicit equivalence, opt-outs and rejected unsupported formats')

# --dense-requant CLI parsing, rejection, and off/none clearing on non-qwen4exp models
run('tiny-lfm.gguf', '--dense-requant', 'q4_k', error="qwen4exp models only")
run('tiny-lfm.gguf', '--dense-requant', 'q4_k+head', error="qwen4exp models only")
run('tiny-lfm.gguf', '--dense-requant', 'q6_k', error='--dense-requant takes')
run('tiny-lfm.gguf', '--dense-requant', 'invalid', error='--dense-requant takes')
run('tiny-lfm.gguf', '--dense-requant', '+head', error='--dense-requant takes')
run('tiny-lfm.gguf', '--dense-requant', 'q4_k+head+head', error='--dense-requant takes')
lfm_default, _ = run('tiny-lfm.gguf')
lfm_off, lfm_off_err = run('tiny-lfm.gguf', '--dense-requant', 'OFF')
lfm_none, lfm_none_err = run('tiny-lfm.gguf', '--dense-requant', 'none')
assert lfm_default == lfm_off == lfm_none
assert 'dense requant' not in lfm_off_err and 'dense requant' not in lfm_none_err


def _gguf_str(s: str) -> bytes:
b = s.encode('utf-8')
return struct.pack('<Q', len(b)) + b


def _pack_tensor_data(name: str, shape: tuple[int, ...], gtype: int, norm: bool = False) -> bytes:
n = 1
for d in shape:
n *= d
if norm:
vals = [1.0] * n
else:
bias = float(len(name))
vals = [0.03 * math.sin(float(i) * 0.079 + bias) for i in range(n)]
if gtype == 0: # F32
return struct.pack(f'<{n}f', *vals)
if gtype == 30: # BF16
raw = struct.pack(f'<{n}f', *vals)
u32 = struct.unpack(f'<{n}I', raw)
return struct.pack(f'<{n}H', *((x >> 16) & 0xFFFF for x in u32))
if gtype == 8: # Q8_0 (32 values -> fp16 d + 32 int8)
assert n % 32 == 0
out = bytearray((n // 32) * 34)
for b in range(n // 32):
blk = vals[b * 32:(b + 1) * 32]
amax = max(abs(v) for v in blk)
d = amax / 127.0
inv = (1.0 / d) if d > 0.0 else 0.0
off = b * 34
struct.pack_into('<e', out, off, d)
for j, v in enumerate(blk):
q = max(-127, min(127, int(round(v * inv))))
out[off + 2 + j] = q & 0xFF
return bytes(out)
if gtype == 2: # Q4_0 (32 values -> fp16 d + 16 packed bytes)
assert n % 32 == 0
out = bytearray((n // 32) * 18)
for b in range(n // 32):
blk = vals[b * 32:(b + 1) * 32]
best = max(blk, key=abs)
d = best / -8.0
inv = (1.0 / d) if d != 0.0 else 0.0
off = b * 18
struct.pack_into('<e', out, off, d)
for j in range(16):
q0 = max(0, min(15, int(blk[j] * inv + 8.5)))
q1 = max(0, min(15, int(blk[j + 16] * inv + 8.5)))
out[off + 2 + j] = q0 | (q1 << 4)
return bytes(out)
raise ValueError(f'unsupported synthetic type {gtype}')


def write_tiny_qwen4exp(path: Path, tied_head: bool = False) -> None:
"""Write a minimal valid 2-layer (1 GDN + 1 Attention) synthetic qwen4exp GGUF."""
arch = 'qwen4exp'
kvs = [
('general.architecture', 8, arch),
(f'{arch}.block_count', 4, 2),
(f'{arch}.embedding_length', 4, 256),
(f'{arch}.vocab_size', 4, 256),
(f'{arch}.attention.layer_norm_rms_epsilon', 6, 1e-5),
(f'{arch}.expert_count', 4, 4),
(f'{arch}.expert_used_count', 4, 2),
(f'{arch}.expert_feed_forward_length', 4, 256),
(f'{arch}.expert_shared_feed_forward_length', 4, 256),
(f'{arch}.hyper_connection.count', 4, 4),
(f'{arch}.hyper_connection.low_rank', 4, 256),
(f'{arch}.attention.head_count', 4, 4),
(f'{arch}.attention.head_count_kv', 4, 1),
(f'{arch}.attention.key_length', 4, 64),
(f'{arch}.attention.value_length', 4, 64),
(f'{arch}.ssm.state_size', 4, 64),
(f'{arch}.ssm.group_count', 4, 2),
(f'{arch}.ssm.time_step_rank', 4, 4),
(f'{arch}.ssm.inner_size', 4, 256),
(f'{arch}.ssm.conv_kernel', 4, 4),
(f'{arch}.rope.freq_base', 6, 10000.0),
(f'{arch}.attention.recurrent_layers', 9, (4, [1, 0])),
]

# (name, shape, ggml_type, is_norm)
# Deliberately mixes Q8_0 (8), BF16 (30), F32 (0), and Q4_0 (2) on dense matrices:
# blk.0.ssm_out.weight is Q4_0 (0.5625 B/elem) so it tests the never-upsize guard.
specs = [
('token_embd.weight', (256, 256), 8, False),
('output_hc_norm.weight', (1024,), 0, True),
('output_hc_down.weight', (1024, 256), 8, False),
('output_hc_up.weight', (256, 1024), 8, False),
]
if not tied_head:
specs.append(('output.weight', (256, 256), 8, False))

for il in (0, 1):
p = f'blk.{il}.'
specs += [
(p + 'hc_attn_norm.weight', (1024,), 0, True),
(p + 'hc_attn_down_inject.weight', (1024, 260), 8, False),
(p + 'hc_attn_up.weight', (256, 1024), 8, False),
(p + 'hc_ffn_norm.weight', (1024,), 0, True),
(p + 'hc_ffn_down_inject.weight', (1024, 260), 30 if il == 0 else 8, False),
(p + 'hc_ffn_up.weight', (256, 1024), 0 if il == 0 else 8, False),
]
if il == 0:
specs += [
(p + 'attn_qkv_gate.weight', (256, 768), 8, False),
(p + 'ssm_beta_alpha.weight', (256, 8), 8, False),
(p + 'ssm_conv1d.weight', (4, 512), 0, False),
(p + 'ssm_dt.bias', (4,), 0, False),
(p + 'ssm_a', (4,), 0, False),
(p + 'ssm_norm.weight', (64,), 0, True),
(p + 'ssm_out.weight', (256, 256), 2, False), # Q4_0: must NEVER be requantized/upsized
]
else:
specs += [
(p + 'attn_q.weight', (256, 512), 8, False),
(p + 'attn_k.weight', (256, 64), 8, False),
(p + 'attn_v.weight', (256, 64), 8, False),
(p + 'attn_q_norm.weight', (64,), 0, True),
(p + 'attn_k_norm.weight', (64,), 0, True),
(p + 'attn_output.weight', (256, 256), 8, False),
]
specs += [
(p + 'ffn_gate_inp.weight', (256, 4), 0, False),
(p + 'ffn_gate_shexp.weight', (256, 256), 8, False),
(p + 'ffn_up_shexp.weight', (256, 256), 8, False),
(p + 'ffn_down_shexp.weight', (256, 256), 8, False),
(p + 'ffn_gate_inp_shexp.weight', (256,), 0, False),
(p + 'ffn_gate_up_exps.weight', (256, 512, 4), 8, False),
(p + 'ffn_down_exps.weight', (256, 256, 4), 8, False),
]

payloads = []
offsets = []
cur = 0
for name, shape, gtype, is_norm in specs:
data = _pack_tensor_data(name, shape, gtype, is_norm)
offsets.append(cur)
payloads.append(data)
cur = (cur + len(data) + 31) & ~31

buf = bytearray()
buf += b'GGUF'
buf += struct.pack('<IQQ', 3, len(specs), len(kvs))
for k, vtype, val in kvs:
buf += _gguf_str(k)
buf += struct.pack('<I', vtype)
if vtype == 4:
buf += struct.pack('<I', val)
elif vtype == 6:
buf += struct.pack('<f', val)
elif vtype == 8:
buf += _gguf_str(val)
elif vtype == 9:
et, items = val
buf += struct.pack('<IQ', et, len(items))
for x in items:
buf += struct.pack('<I', x)
for (name, shape, gtype, _), off in zip(specs, offsets):
buf += _gguf_str(name)
buf += struct.pack('<I', len(shape))
for d in shape:
buf += struct.pack('<Q', d)
buf += struct.pack('<IQ', gtype, off)

pad = (-len(buf)) & 31
buf += b'\x00' * pad
for data in payloads:
buf += data
p = (-len(data)) & 31
if p:
buf += b'\x00' * p
path.write_bytes(buf)


def parse_requant_log(stderr: str, spec: str) -> tuple[int, float]:
m = re.search(
rf'strata-poly: dense requant \({re.escape(spec)}\): (\d+) tensors requantized, saved ([0-9.]+) MiB VRAM',
stderr,
)
assert m, f'missing dense requant log for {spec!r} in:\n{stderr}'
return int(m.group(1)), float(m.group(2))


with tempfile.TemporaryDirectory() as tmp:
q4_path = Path(tmp) / 'tiny-qwen4exp.gguf'
q4_tied_path = Path(tmp) / 'tiny-qwen4exp-tied.gguf'
write_tiny_qwen4exp(q4_path, tied_head=False)
write_tiny_qwen4exp(q4_tied_path, tied_head=True)

# Default off is byte-identical to --dense-requant off / none and emits no requant log
q4_def, q4_def_err = run(q4_path)
q4_off, q4_off_err = run(q4_path, '--dense-requant', 'off')
q4_none, q4_none_err = run(q4_path, '--dense-requant', 'NONE')
assert q4_def == q4_off == q4_none
assert 'dense requant' not in q4_def_err and 'dense requant' not in q4_off_err and 'dense requant' not in q4_none_err

# q4_k (and uppercase normalization): 21 dense tensors requantized (excludes Q4_0 ssm_out, beta_alpha, routers, output)
q4_q4k_out, q4_q4k_err = run(q4_path, '--dense-requant', 'q4_k')
q4_q4k_up_out, q4_q4k_up_err = run(q4_path, '--dense-requant', 'Q4_K')
n_q4k, saved_q4k = parse_requant_log(q4_q4k_err, 'q4_k')
n_q4k_up, saved_q4k_up = parse_requant_log(q4_q4k_up_err, 'q4_k')
assert n_q4k == 21 and saved_q4k > 0.0, (n_q4k, saved_q4k)
assert (n_q4k_up, saved_q4k_up) == (n_q4k, saved_q4k) and q4_q4k_out == q4_q4k_up_out

# q4_k+head: exactly +1 tensor (output.weight) and strictly more MiB saved
_, q4_head_err = run(q4_path, '--dense-requant', 'Q4_K+HEAD')
n_head, saved_head = parse_requant_log(q4_head_err, 'q4_k+head')
assert n_head == 22 and saved_head >= saved_q4k, (n_head, saved_head, saved_q4k)

# q5_k: still 21 tensors (proves Q4_0 blk.0.ssm_out.weight was NOT upsized to Q5_K!)
_, q4_q5k_err = run(q4_path, '--dense-requant', 'q5_k')
n_q5k, saved_q5k = parse_requant_log(q4_q5k_err, 'q5_k')
assert n_q5k == 21 and 0.0 < saved_q5k < saved_q4k, (n_q5k, saved_q5k, saved_q4k)

# Other supported base formats all execute cleanly
for fmt in ('q4_0', 'q5_0', 'iq4_nl'):
_, fmt_err = run(q4_path, '--dense-requant', fmt)
n_fmt, saved_fmt = parse_requant_log(fmt_err, fmt)
assert n_fmt == 21 and saved_fmt > 0.0, (fmt, n_fmt, saved_fmt)

# Tied embeddings (no output.weight): +head requantizes GPU output_ while keeping host tok_embd_ intact
_, tied_err = run(q4_tied_path, '--dense-requant', 'q4_k+head')
n_tied, saved_tied = parse_requant_log(tied_err, 'q4_k+head')
assert n_tied == 22 and saved_tied > 0.0, (n_tied, saved_tied)

# --cache-bias on qwen4exp with partial VRAM expert cache (STRATA_GPU_EXPERTS=4 out of 8 total)
cb_env = dict(os.environ, STRATA_GPU_EXPERTS='4')
_, cb_err = run(q4_path, '--cache-bias', '0.05', env=cb_env)
assert 'cache bias 0.05' in cb_err, cb_err

print('Metal defaults: effective settings, explicit equivalence, opt-outs, qwen4exp dense-requant and cache-bias')
Loading
Loading