Merge f-quants (945fee23) into f-qwen36: the K-quant CPU pool rows, libstrata_kq, the K-quant GEMV work
This commit is contained in:
commit
3e11f786af
30 files changed
+2113
-126
No files matched your search
@@ -7,3 +7,6 @@ bench/prompts/** -text
|
||||
|
||||
# copies of real packs' native_experts.txt, parsed byte for byte by tests/core/expert_layout_test.cpp
|
||||
tests/data/native_experts/** -text
|
||||
|
||||
# the quant yardstick's text set: tokenized byte for byte (set.ids.json), never convert its line endings
|
||||
data/quant_quality/** -text
|
||||
+60
-16
@@ -70,14 +70,17 @@ if(STRATA_HIP_GFX906)
|
||||
endif()
|
||||
option(STRATA_ENABLE_HIP "Build the HIP targets for wave32 AMD GPUs (gfx1100, gfx1201; gfx1012/gfx1030 unvalidated)" OFF)
|
||||
option(STRATA_PREFILL_MMQ "Build the optional GGML MMQ prefill path for HIP" OFF)
|
||||
# CUDA: MMQ prompt kernels for Q4_K / Q5_K / Q5_1 (Unsloth's UD-Q4_K_XL experts). Off by default: the engine loads
|
||||
# every kernel when it starts (CUDA_MODULE_LOADING=EAGER), so these took ~5 MB of VRAM - 1-3 expert slots - from every
|
||||
# model, and the UD-Q4_K_XL prompt is SSD-bound with or without them (docs/UNSLOTH_Q4.md)
|
||||
option(STRATA_MMQ_KQUANTS "Build the MMQ prompt kernels for Q4_K / Q5_K / Q5_1 / Q6_K: the CUDA experts of Unsloth's UD-Q4_K_XL, and on HIP the dense GGUF projections (STRATA_DENSE_MMQ)" OFF)
|
||||
# CUDA: Q6_K gate/up in the grouped expert kernels (Unsloth's UD-Q6_K_XL, docs/UNSLOTH_Q6.md). Off by default: every
|
||||
# grouped-kernel instance is loaded when the engine starts (CUDA_MODULE_LOADING=EAGER), so one more costs VRAM that
|
||||
# every other model would lose as expert slots (PR #860 review)
|
||||
option(STRATA_Q6K_EXPERTS "Build the Q6_K gate/up grouped expert kernels (UD-Q6_K_XL)" OFF)
|
||||
# MMQ prompt kernels for Q4_K / Q5_K / Q5_1 / Q6_K (Unsloth's UD-Q4/Q5/Q6_K_XL experts; on HIP also the dense GGUF
|
||||
# projections, STRATA_DENSE_MMQ). On by default since MODEL-UPDATE Phase 1: on CUDA they are their own library
|
||||
# (strata_kq, loaded only for a model with these formats: the engine loads every kernel of its own binary at start,
|
||||
# CUDA_MODULE_LOADING=EAGER, and these took ~3.8 MB of VRAM - 3 IQ3_XXS expert slots on a P100 - from every model); on
|
||||
# HIP a code object loads on first use, so they cost other models nothing there (R9700: the same slots). Used at run
|
||||
# time with STRATA_MMQ_KQ=1 (opt-in: it changes the prompt's rounding against the FP16 path).
|
||||
option(STRATA_MMQ_KQUANTS "Build the MMQ prompt kernels for Q4_K / Q5_K / Q5_1 / Q6_K: the experts of Unsloth's K-quant files, and on HIP the dense GGUF projections (STRATA_DENSE_MMQ)" ON)
|
||||
# Q6_K gate/up in the grouped expert kernels (Unsloth's UD-Q6_K_XL, and layer 2 of UD-Q5_K_XL; docs/QUANTS.md). On by
|
||||
# default since MODEL-UPDATE Phase 1: one more instance per grouped kernel in iq_kernels.cu, +19 KB of sm_60 code,
|
||||
# measured to leave every expert-cache slot count as it was (P100, R9700). -DSTRATA_Q6K_EXPERTS=OFF drops it.
|
||||
option(STRATA_Q6K_EXPERTS "Build the Q6_K gate/up grouped expert kernels (UD-Q6_K_XL, UD-Q5_K_XL)" ON)
|
||||
if(STRATA_Q6K_EXPERTS)
|
||||
add_compile_definitions(STRATA_Q6K_EXPERTS=1)
|
||||
endif()
|
||||
@@ -1340,6 +1343,9 @@ if(STRATA_NATIVE_EXPERTS)
|
||||
# against ggml-cpu's dot, on random blocks; --bench: ms per expert on one thread, the weights streamed from DRAM
|
||||
add_executable(iq_avx2_parity src/kernels/cpu/iq_avx2_parity.cpp)
|
||||
target_link_libraries(iq_avx2_parity PRIVATE strata_kernels_cpu)
|
||||
# MODEL-UPDATE: the pool's expert rows per format on T threads against the RAM bandwidth (a benchmark, no test)
|
||||
add_executable(kq_cpu_bench src/kernels/cpu/kq_cpu_bench.cpp)
|
||||
target_link_libraries(kq_cpu_bench PRIVATE strata_kernels_cpu)
|
||||
if(STRATA_BUILD_TESTS)
|
||||
add_test(NAME iq_avx2_parity COMMAND iq_avx2_parity)
|
||||
add_test(NAME iq_avx2_parity_iq3s_mt1 COMMAND ${CMAKE_COMMAND} -E env STRATA_IQ3S_MT1=1 $<TARGET_FILE:iq_avx2_parity>)
|
||||
@@ -1379,14 +1385,18 @@ if(STRATA_NATIVE_EXPERTS)
|
||||
add_library(strata_mmq STATIC src/prefill/moe_mmq.cu src/prefill/moe_fused.cu src/prefill/moe_fused_iq.cu
|
||||
src/prefill/ggml_cuda_host.cu ${_strata_mmq}/quantize.cu)
|
||||
# q8_0: the drafter's matrices (E-9); STRATA_ORCA_Q4KS_MMQ adds q5_0 (#296, in _strata_mmq_types), and
|
||||
# STRATA_MMQ_KQUANTS q4_k q5_k q5_1, the experts of Unsloth's UD-Q4_K_XL (docs/UNSLOTH_Q4.md; the dispatch
|
||||
# follows eddoursul/Strata 7706c1b); q6_k is HIP only
|
||||
# STRATA_MMQ_KQUANTS q4_k q5_k q5_1 q6_k, the experts of Unsloth's UD-Q4/Q5/Q6_K_XL (docs/QUANTS.md; the dispatch
|
||||
# follows eddoursul/Strata 7706c1b). MODEL-UPDATE Phase 1: on CUDA they are a library of their own, strata_kq
|
||||
# (below), loaded only for a model with these experts: the engine loads every kernel of its own binary at start
|
||||
# (CUDA_MODULE_LOADING=EAGER), and these four took ~3.8 MB of VRAM (3 expert slots of IQ3_XXS on a P100) from every
|
||||
# model. gfx906 (HIP: code objects load on first use) keeps them in strata_mmq.
|
||||
set(_strata_mmq_cuda_types ${_strata_mmq_types})
|
||||
if(STRATA_MMQ_KQUANTS)
|
||||
list(APPEND _strata_mmq_cuda_types q4_k q5_k q5_1)
|
||||
if(STRATA_Q6K_EXPERTS OR STRATA_HIP_GFX906) # UD-Q6_K_XL gate/up (docs/UNSLOTH_Q6.md),
|
||||
list(APPEND _strata_mmq_cuda_types q6_k) # and gfx906: moe_mmq.cu calls it under __HIPCC__
|
||||
endif()
|
||||
set(_strata_kq_types q4_k q5_k q5_1 q6_k)
|
||||
set(_strata_kq_dso OFF)
|
||||
if(STRATA_MMQ_KQUANTS AND STRATA_HIP_GFX906)
|
||||
list(APPEND _strata_mmq_cuda_types ${_strata_kq_types})
|
||||
elseif(STRATA_MMQ_KQUANTS)
|
||||
set(_strata_kq_dso ON)
|
||||
endif()
|
||||
foreach(_t IN LISTS _strata_mmq_cuda_types)
|
||||
target_sources(strata_mmq PRIVATE ${_strata_mmq}/template-instances/mmq-instance-${_t}.cu)
|
||||
@@ -1405,6 +1415,35 @@ if(STRATA_NATIVE_EXPERTS)
|
||||
if(STRATA_MMQ_KQUANTS)
|
||||
target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_KQUANTS=1)
|
||||
endif()
|
||||
if(_strata_kq_dso)
|
||||
# strata_kq: the K-quant MMQ instances with their own copy of ggml_cuda_host.cu's symbols and the static CUDA
|
||||
# runtime, next to the engine (libstrata_kq.so / strata_kq.dll); moe_mmq.cu opens it when a model asks for one
|
||||
# of these formats (STRATA_MMQ_KQ=1). Without the file the engine runs them on the FP16 prompt path, as before.
|
||||
target_compile_definitions(strata_mmq PRIVATE STRATA_KQ_DSO=1)
|
||||
target_sources(strata_mmq PRIVATE src/prefill/mmq_kq_loader.cpp)
|
||||
if(NOT WIN32)
|
||||
target_link_libraries(strata_mmq PUBLIC ${CMAKE_DL_LIBS})
|
||||
endif()
|
||||
add_library(strata_kq SHARED src/prefill/mmq_kq_lib.cu src/prefill/ggml_cuda_host.cu)
|
||||
foreach(_t IN LISTS _strata_kq_types)
|
||||
target_sources(strata_kq PRIVATE ${_strata_mmq}/template-instances/mmq-instance-${_t}.cu)
|
||||
endforeach()
|
||||
target_include_directories(strata_kq PRIVATE ${_strata_gg}/include ${_strata_gg}/src ${_strata_mmq}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/include)
|
||||
target_compile_options(strata_kq PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda -use_fast_math>)
|
||||
if(MSVC)
|
||||
target_compile_options(strata_kq PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:-Xcompiler=/bigobj>)
|
||||
endif()
|
||||
set_target_properties(strata_kq PROPERTIES CUDA_RUNTIME_LIBRARY Static POSITION_INDEPENDENT_CODE ON
|
||||
CXX_VISIBILITY_PRESET hidden CUDA_VISIBILITY_PRESET hidden)
|
||||
# ggml-base is static: position-independent so a shared library can hold it (the same code otherwise)
|
||||
set_target_properties(ggml-base PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
||||
target_link_libraries(strata_kq PRIVATE ggml-base)
|
||||
if(TARGET CUDA::cuda_driver)
|
||||
target_link_libraries(strata_kq PRIVATE CUDA::cuda_driver)
|
||||
endif()
|
||||
add_dependencies(strata_mmq strata_kq)
|
||||
endif()
|
||||
if(STRATA_ORCA_Q4KS_MMQ)
|
||||
target_compile_definitions(strata_mmq PRIVATE STRATA_ORCA_Q4KS_MMQ=1)
|
||||
endif()
|
||||
@@ -1427,7 +1466,8 @@ if(STRATA_NATIVE_EXPERTS)
|
||||
add_executable(prefill_mmq_kquant_test tests/cuda/prefill_mmq_kquant_test.cpp)
|
||||
target_link_libraries(prefill_mmq_kquant_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target})
|
||||
add_test(NAME prefill_mmq_kquant_test COMMAND prefill_mmq_kquant_test)
|
||||
set_tests_properties(prefill_mmq_kquant_test PROPERTIES TIMEOUT 120)
|
||||
# the K-quant MMQ is opt-in at run time (STRATA_MMQ_KQ=1), and on CUDA it is strata_kq next to the test
|
||||
set_tests_properties(prefill_mmq_kquant_test PROPERTIES TIMEOUT 120 ENVIRONMENT STRATA_MMQ_KQ=1)
|
||||
endif()
|
||||
elseif(STRATA_PREFILL_MMQ)
|
||||
# Compile only the pinned GGML MMQ and activation-quantizer sources used by prefill. This uses
|
||||
@@ -1508,6 +1548,10 @@ if(STRATA_NATIVE_EXPERTS)
|
||||
add_executable(native_expert_bench src/kernels/native_expert_bench.cpp)
|
||||
target_include_directories(native_expert_bench PRIVATE ${_strata_gpu_include_directories})
|
||||
target_link_libraries(native_expert_bench PRIVATE strata_kernels strata_kernels_cpu strata_artifact ${_strata_gpu_runtime_target})
|
||||
# MODEL-UPDATE: the dense Q8_0 GEMVs at the engine's shapes against the memory bandwidth (a benchmark, no test)
|
||||
add_executable(q8_gemv_bench src/kernels/q8_gemv_bench.cpp)
|
||||
target_include_directories(q8_gemv_bench PRIVATE ${_strata_gpu_include_directories})
|
||||
target_link_libraries(q8_gemv_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target})
|
||||
if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA)
|
||||
# Unsloth UD-Q4_K_XL's three expert pairs (and Q8_0 alone, its embedding) on synthetic ggml-quantized weights
|
||||
# at 2560/640: GPU and CPU experts against the float reference, GPU dequantizers against to_float.
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
<|im_start|>system
|
||||
You are a coding agent working in the user's repository. You can call tools to read files, search the code and run commands. Keep changes small and explain what you did.<|im_end|>
|
||||
<|im_start|>user
|
||||
The test `test_parse_duration` fails since yesterday's merge. Can you find out why and fix it?<|im_end|>
|
||||
<|im_start|>assistant
|
||||
<think>
|
||||
I should run the failing test first to see the actual error message, then look at the function it tests.
|
||||
</think>
|
||||
|
||||
<tool_call>
|
||||
{"name": "run_command", "arguments": {"command": "python -m pytest tests/test_time_utils.py -k test_parse_duration -q"}}
|
||||
</tool_call><|im_end|>
|
||||
<|im_start|>user
|
||||
<tool_response>
|
||||
F [100%]
|
||||
=================================== FAILURES ===================================
|
||||
_____________________________ test_parse_duration ______________________________
|
||||
|
||||
def test_parse_duration():
|
||||
assert parse_duration("90s") == 90
|
||||
assert parse_duration("5m") == 300
|
||||
> assert parse_duration("1h30m") == 5400
|
||||
E ValueError: invalid duration: '1h30m'
|
||||
|
||||
tests/test_time_utils.py:14: ValueError
|
||||
1 failed, 11 deselected in 0.21s
|
||||
</tool_response><|im_end|>
|
||||
<|im_start|>assistant
|
||||
<think>
|
||||
Single units work but a combined value fails. Let me read the parser.
|
||||
</think>
|
||||
|
||||
<tool_call>
|
||||
{"name": "read_file", "arguments": {"path": "src/time_utils.py", "start_line": 1, "end_line": 40}}
|
||||
</tool_call><|im_end|>
|
||||
<|im_start|>user
|
||||
<tool_response>
|
||||
import re
|
||||
|
||||
_UNITS = {"s": 1, "m": 60, "h": 3600, "d": 86400}
|
||||
_PART = re.compile(r"^(\d+)([smhd])$")
|
||||
|
||||
|
||||
def parse_duration(text: str) -> int:
|
||||
"""Parse a duration like '90s', '5m' or '1h30m' into seconds."""
|
||||
text = text.strip().lower()
|
||||
if not text:
|
||||
raise ValueError("empty duration")
|
||||
m = _PART.match(text)
|
||||
if m is None:
|
||||
raise ValueError(f"invalid duration: {text!r}")
|
||||
return int(m.group(1)) * _UNITS[m.group(2)]
|
||||
</tool_response><|im_end|>
|
||||
<|im_start|>assistant
|
||||
<think>
|
||||
The regex is anchored at both ends and matches exactly one number-unit pair, so "1h30m" can never match. The docstring promises combined values. Let me check git history to see what the merge changed.
|
||||
</think>
|
||||
|
||||
<tool_call>
|
||||
{"name": "run_command", "arguments": {"command": "git log -p -n 1 -- src/time_utils.py | head -40"}}
|
||||
</tool_call><|im_end|>
|
||||
<|im_start|>user
|
||||
<tool_response>
|
||||
commit 4e1b9c2f7a0d (Merge branch 'cleanup-regex')
|
||||
Simplify duration parsing
|
||||
|
||||
-_PART = re.compile(r"(\d+)([smhd])")
|
||||
+_PART = re.compile(r"^(\d+)([smhd])$")
|
||||
@@ def parse_duration(text: str) -> int:
|
||||
- total = 0
|
||||
- pos = 0
|
||||
- for m in _PART.finditer(text):
|
||||
- if m.start() != pos:
|
||||
- raise ValueError(f"invalid duration: {text!r}")
|
||||
- total += int(m.group(1)) * _UNITS[m.group(2)]
|
||||
- pos = m.end()
|
||||
- if pos != len(text):
|
||||
- raise ValueError(f"invalid duration: {text!r}")
|
||||
- return total
|
||||
+ m = _PART.match(text)
|
||||
+ if m is None:
|
||||
+ raise ValueError(f"invalid duration: {text!r}")
|
||||
+ return int(m.group(1)) * _UNITS[m.group(2)]
|
||||
</tool_response><|im_end|>
|
||||
<|im_start|>assistant
|
||||
The cleanup merge replaced the loop over all number-unit pairs with a single anchored match, so only one unit per string is accepted now. I will restore the loop, which also rejects garbage between the parts.
|
||||
|
||||
<tool_call>
|
||||
{"name": "edit_file", "arguments": {"path": "src/time_utils.py", "old": "_PART = re.compile(r\"^(\\d+)([smhd])$\")", "new": "_PART = re.compile(r\"(\\d+)([smhd])\")"}}
|
||||
</tool_call><|im_end|>
|
||||
<|im_start|>user
|
||||
<tool_response>
|
||||
OK: 1 replacement in src/time_utils.py
|
||||
</tool_response><|im_end|>
|
||||
<|im_start|>assistant
|
||||
<tool_call>
|
||||
{"name": "edit_file", "arguments": {"path": "src/time_utils.py", "old": " m = _PART.match(text)\n if m is None:\n raise ValueError(f\"invalid duration: {text!r}\")\n return int(m.group(1)) * _UNITS[m.group(2)]", "new": " total = 0\n pos = 0\n for m in _PART.finditer(text):\n if m.start() != pos:\n raise ValueError(f\"invalid duration: {text!r}\")\n total += int(m.group(1)) * _UNITS[m.group(2)]\n pos = m.end()\n if pos != len(text):\n raise ValueError(f\"invalid duration: {text!r}\")\n return total"}}
|
||||
</tool_call><|im_end|>
|
||||
<|im_start|>user
|
||||
<tool_response>
|
||||
OK: 1 replacement in src/time_utils.py
|
||||
</tool_response><|im_end|>
|
||||
<|im_start|>assistant
|
||||
<tool_call>
|
||||
{"name": "run_command", "arguments": {"command": "python -m pytest tests/test_time_utils.py -q"}}
|
||||
</tool_call><|im_end|>
|
||||
<|im_start|>user
|
||||
<tool_response>
|
||||
............ [100%]
|
||||
12 passed in 0.19s
|
||||
</tool_response><|im_end|>
|
||||
<|im_start|>assistant
|
||||
All 12 tests in `tests/test_time_utils.py` pass again. The cause was the `cleanup-regex` merge: it anchored the pattern with `^...$` and replaced the loop with one `match`, so a duration with several parts such as `1h30m` was rejected. I restored the previous loop, which sums every number-unit pair and still raises `ValueError` for text between or after the parts (for example `1h x30m`). You may want to add a test for that rejection case so the next simplification does not drop it.<|im_end|>
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Minimal GGUF v3 header reader - no ggml, no gguf-py.
|
||||
|
||||
Written because the `gguf` PyPI package cannot open this artifact: its `GGMLQuantizationType`
|
||||
enum has no member for type 42 (`Q2_0`), which is newer than the library. That is itself a P0.S6
|
||||
finding - the format this engine is specialized for is ahead of the standard tooling.
|
||||
|
||||
This is the reference implementation for `src/artifact/` (architecture §15: "GGUF v3 reader (mmap,
|
||||
no ggml dependency)"). It parses the header only; tensor data is never read.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import struct
|
||||
from typing import Any
|
||||
|
||||
GGUF_MAGIC = 0x46554747 # "GGUF" little-endian
|
||||
|
||||
# ggml_type values. 42 = Q2_0, the GSQ-RCO routed-expert encoding, absent from gguf-py as of 0.19.
|
||||
GGML_TYPES: dict[int, str] = {
|
||||
0: "F32", 1: "F16", 2: "Q4_0", 3: "Q4_1", 4: "Q4_2", 5: "Q4_3", 6: "Q5_0", 7: "Q5_1",
|
||||
8: "Q8_0", 9: "Q8_1", 10: "Q2_K", 11: "Q3_K", 12: "Q4_K", 13: "Q5_K", 14: "Q6_K",
|
||||
15: "Q8_K", 16: "IQ2_XXS", 17: "IQ2_XS", 18: "IQ3_XXS", 19: "IQ1_S", 20: "IQ4_NL",
|
||||
21: "IQ3_S", 22: "IQ2_S", 23: "IQ4_XS", 24: "I8", 25: "I16", 26: "I32", 27: "I64",
|
||||
28: "F64", 29: "IQ1_M", 30: "BF16", 31: "Q4_0_4_4", 32: "Q4_0_4_8", 33: "Q4_0_8_8",
|
||||
34: "TQ1_0", 35: "TQ2_0", 36: "IQ4_NL_4_4", 37: "IQ4_NL_4_8", 38: "IQ4_NL_8_8",
|
||||
39: "MXFP4", 40: "NVFP4", 41: "Q4_0_8_8", 42: "Q2_0",
|
||||
}
|
||||
|
||||
# GGUF metadata value type ids
|
||||
GGUF_META = {
|
||||
0: ("u8", 1), 1: ("i8", 1), 2: ("u16", 2), 3: ("i16", 2), 4: ("u32", 4), 5: ("i32", 4),
|
||||
6: ("f32", 4), 7: ("bool", 1), 8: ("string", None), 9: ("array", None),
|
||||
10: ("u64", 8), 11: ("i64", 8), 12: ("f64", 8),
|
||||
}
|
||||
|
||||
# ggml block geometry for the encodings this model uses: (block elements, bytes per block)
|
||||
# This is what makes a per-tensor byte count checkable, and it is the contract the kernels share.
|
||||
BLOCK_GEOMETRY: dict[str, tuple[int, int]] = {
|
||||
"F32": (1, 4), "F16": (1, 2), "BF16": (1, 2), "F64": (1, 8),
|
||||
"Q4_0": (32, 18), "Q4_1": (32, 20), "Q5_0": (32, 22), "Q5_1": (32, 24),
|
||||
"Q8_0": (32, 34), "Q8_1": (32, 36),
|
||||
"Q2_K": (256, 84), "Q3_K": (256, 110), "Q4_K": (256, 144), "Q5_K": (256, 176),
|
||||
"Q6_K": (256, 210), "Q8_K": (256, 292),
|
||||
"IQ2_XXS": (256, 66), "IQ2_XS": (256, 74), "IQ3_XXS": (256, 98), "IQ1_S": (256, 50),
|
||||
"IQ4_NL": (32, 18), "IQ3_S": (256, 110), "IQ2_S": (256, 82), "IQ4_XS": (256, 136),
|
||||
"IQ1_M": (256, 56), "Q2_0": (64, 18), "MXFP4": (32, 17), "NVFP4": (64, 36),
|
||||
}
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class TensorInfo:
|
||||
name: str
|
||||
shape: list[int]
|
||||
type_id: int
|
||||
type_name: str
|
||||
offset: int
|
||||
|
||||
@property
|
||||
def elements(self) -> int:
|
||||
n = 1
|
||||
for d in self.shape:
|
||||
n *= d
|
||||
return n
|
||||
|
||||
def expected_bytes(self) -> int | None:
|
||||
geom = BLOCK_GEOMETRY.get(self.type_name)
|
||||
if geom is None:
|
||||
return None
|
||||
block_elems, block_bytes = geom
|
||||
if self.elements % block_elems:
|
||||
return None
|
||||
return self.elements // block_elems * block_bytes
|
||||
|
||||
|
||||
class GGUFFile:
|
||||
def __init__(self, path: pathlib.Path):
|
||||
self.path = pathlib.Path(path)
|
||||
self.metadata: dict[str, Any] = {}
|
||||
self.tensors: list[TensorInfo] = []
|
||||
self.version = 0
|
||||
self.alignment = 32
|
||||
with self.path.open("rb") as fh:
|
||||
self._parse(fh)
|
||||
self.data_start = self._data_start
|
||||
|
||||
# ------------------------------------------------------------------ internals
|
||||
def _parse(self, fh) -> None:
|
||||
magic = struct.unpack("<I", fh.read(4))[0]
|
||||
if magic != GGUF_MAGIC:
|
||||
raise ValueError(f"{self.path.name}: not a GGUF file (magic {magic:#x})")
|
||||
self.version, n_tensors, n_kv = struct.unpack("<IQQ", fh.read(20))
|
||||
if self.version != 3:
|
||||
raise ValueError(f"{self.path.name}: GGUF v{self.version}, this reader handles v3")
|
||||
for _ in range(n_kv):
|
||||
key = self._str(fh)
|
||||
self.metadata[key] = self._value(fh)
|
||||
for _ in range(n_tensors):
|
||||
name = self._str(fh)
|
||||
(n_dims,) = struct.unpack("<I", fh.read(4))
|
||||
shape = list(struct.unpack(f"<{n_dims}Q", fh.read(8 * n_dims)))
|
||||
type_id, offset = struct.unpack("<IQ", fh.read(12))
|
||||
self.tensors.append(TensorInfo(name, shape, type_id,
|
||||
GGML_TYPES.get(type_id, f"type{type_id}"), offset))
|
||||
align = self.metadata.get("general.alignment")
|
||||
if isinstance(align, int) and align:
|
||||
self.alignment = align
|
||||
pos = fh.tell()
|
||||
self._data_start = (pos + self.alignment - 1) // self.alignment * self.alignment
|
||||
|
||||
def _str(self, fh) -> str:
|
||||
(n,) = struct.unpack("<Q", fh.read(8))
|
||||
return fh.read(n).decode("utf-8", "replace")
|
||||
|
||||
def _value(self, fh):
|
||||
(t,) = struct.unpack("<I", fh.read(4))
|
||||
name, size = GGUF_META[t]
|
||||
if name == "string":
|
||||
return self._str(fh)
|
||||
if name == "array":
|
||||
(et,) = struct.unpack("<I", fh.read(4))
|
||||
(count,) = struct.unpack("<Q", fh.read(8))
|
||||
ename, esize = GGUF_META[et]
|
||||
if ename == "string":
|
||||
return [self._str(fh) for _ in r
|
||||
@@ -0,0 +1,49 @@
|
||||
- **GPU (VRAM):** attention and DeltaNet mixers, the gated-residual weights, routers, shared experts, output head, the MTP
|
||||
draft layer, the KV cache (from 64K: only its most-read part, the rest streams from RAM), and an **expert cache** that fills the rest of VRAM with the most-used experts (it adapts to
|
||||
the conversation while you chat).
|
||||
- **RAM:** all 24,576 experts, pinned. The CPU computes the experts that are not on the GPU **in place**, at the same time
|
||||
as the GPU works on the cached ones (AVX-512 / AVX2 kernels, ggml's for the i-quants).
|
||||
- **SSD:** the 28.8 GB n-gram table, a few rows per token, read unbuffered past the OS cache (`--ple-io direct`, the
|
||||
default, made for SSDs; on a rotational disk `--ple-io ram` keeps the table in RAM, #605). A start-up probe warns when direct reads measure slow (under 15K rows/s) but never switches by itself (since 0.1.43.1; `STRATA_PLE_AUTO_MMAP=1` brings back the 0.1.42 switch to `--ple-io mmap`): the bar is calibrated for NVMe, a SATA SSD tops out at 10-14K rows/s with direct's 16 reads in flight, and on one (Linux, 77.8K-token prompt) mmap read 2.1K rows/s against direct's 14.4K (#2040), while on a Windows box with a slow mapped file mmap stalled prompts (#1984). The engine reads the table
|
||||
in the format the GGUF has it: IQ4_NL (the default table), Q4_0, Q5_0, Q5_1, Q8_0, FP8 (E4M3 with a scale) or BF16.
|
||||
Measured on 4,000 random rows against the checkpoint's own BF16 table, the mean per-row error is Q8_0 0.53%, FP8 2.64%,
|
||||
Q5_1 3.78%, Q5_0 4.25%, IQ4_NL 7.60%, Q4_1 7.80%, Q4_0 8.55% (a Q8_0 table is 54 GB, an IQ4_NL one 28.8 GB). On the Q2_0 model, 700 teacher-forced tokens, the mean KL against the BF16 table is 0.0117 (Q5_0), 0.0121 (Q5_1), 0.0125
|
||||
(Q8_0), 0.0128 (FP8), 0.0140 (Q4_0) and 0.0146 (IQ4_NL), with the perplexity within 1% of BF16's either way: any change to the
|
||||
table moves the 2-bit model by about 0.012, so the formats are hard to tell apart. Setup does not offer another table;
|
||||
it only changes which GGUF the engine is given.
|
||||
- **Speculation:** the model's own MTP layer drafts up to 3 tokens; one pass over all 48 layers checks them. 2.4-3.2
|
||||
tokens per pass on average. When the reply repeats the context (code edits, quoted text), **prompt lookup** (engine
|
||||
0.1.7) drafts up to 5 tokens from the earlier copy, but only where its measured acceptance and cost say it pays:
|
||||
code edits 6-11% faster, other text unchanged. The drafts are checked like the MTP's, so the output is the same.
|
||||
- **Prompts** are processed in chunks of up to 8,192 tokens (`--prefill auto`; 32,768 opt-in) with the experts
|
||||
streamed to the GPU over PCIe. Since engine 0.1.39b (#583) the streamed ring is sized in bytes for the pack (a
|
||||
native pack with bigger blobs gets fewer ring slots and keeps more cache slots) and `--prefill auto` picks the
|
||||
largest chunk that keeps that ring full. It only gives up ring slots where 0.1.39's rule held the chunk at 4,096
|
||||
tokens or less; from 6,144 on it keeps 0.1.39's ring and only looks for a bigger chunk beside it (shrinking the
|
||||
ring there measured slower: the Coder -12%), and a prompt that fits 0.1.39's chunk keeps 0.1.39's ring (one
|
||||
chunk: a smaller ring only slowed it). RTX 5070, 32K prompts against `STRATA_RING_BYTES=0`, 2-3 interleaved
|
||||
rounds: IQ3_XXS +18.5% at a 1,500-slot cache and +9% in another memory state, the Coder +3%, IQ3_S unchanged; 4K
|
||||
prompts unchanged (-0.7% to +1.1%, bit-identical). Q2_0 (a fixed `--prefill 2048`) is not affected. It changes
|
||||
the bits of a long prompt against 0.1.39 (the experts go through a different
|
||||
mix of cached and streamed groups). Measured quality, teacher-forced over the next 2,001 tokens of a long document
|
||||
against the FP16 prompt path (IQ3_XXS, `--prefill auto`): 8K prompt KL 0.042 (0.1.39: 0.054), top-1 agreement
|
||||
93.5% (92.2%); 32K prompt KL 0.020 (0.019), top-1 95.3% (95.0%) - the same band as before. `STRATA_RING_BYTES=0`
|
||||
restores 0.1.39's ring, loan and chunk choice.
|
||||
|
||||
The full story, with measurements, bottlenecks and what comes next: **[docs/paper/Strata-Paper.pdf](paper/Strata-Paper.pdf)**.
|
||||
|
||||
---
|
||||
|
||||
## Credits and licenses
|
||||
|
||||
Strata itself: [MIT](../LICENSE). The model files are not part of it; their licenses apply to them (below).
|
||||
|
||||
- Model: [Qwen/Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next) by the Qwen team; quantizations:
|
||||
[ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF).
|
||||
The Coder: [ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF)
|
||||
(Apache-2.0 per its card); its support in Strata came from @pjgmobile's PR #54.
|
||||
Swift 1.5: [ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF](https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF)
|
||||
by UkisAI. Their licenses apply to the weights.
|
||||
- [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp) (MIT): the i-quant formats, the GPU dot products and
|
||||
dequantizers transcribed in `src/kernels/cuda/iq_kernels.cu`, the CPU backend linked for the i-quant experts, the
|
||||
`mtmd` library behind the image encoder (`tools/vision/`), and `gguf-py` use
|
||||
@@ -0,0 +1,17 @@
|
||||
The lighthouse at the end of the northern breakwater had been automated for almost forty years, but the town still sent someone out to it every Thursday. Nobody remembered who had made the rule, and nobody had ever written it down. It was simply understood that on Thursday afternoon, when the ferry had left and the fish market had been hosed clean, one person would walk the length of the stone pier, unlock the iron door with the key that hung behind the counter of the harbour office, climb the hundred and twelve steps, and look.
|
||||
|
||||
For most of that time the person had been Margaret Hale, who ran the chandlery and claimed she needed the exercise. When her knees finally gave out, the key passed to her grandson Tomas, who was fourteen and considered the whole business a waste of a perfectly good afternoon. He said so, loudly, for the first three weeks. On the fourth Thursday a storm came in early from the west, and he found himself at the top of the tower watching a small sailing boat fight its way past the outer rocks with a torn jib and nobody visibly at the helm.
|
||||
|
||||
He did what his grandmother had told him to do, which was nothing dramatic. He wrote down the time, the direction of the wind, the name painted on the stern, and the fact that he could see only one person on deck. Then he walked back down the hundred and twelve steps, crossed the pier with his hood pulled tight, and told the harbour master, who telephoned the lifeboat station. The boat was towed in an hour later. Its skipper, a retired schoolteacher who had been sailing alone from the islands, had broken his wrist when the boom swung across and had been steering with his feet.
|
||||
|
||||
The story was in the local paper the following week, and Tomas was embarrassed by it, mostly because the photograph showed him in his school uniform. What stayed with him was something else. On the walk back along the pier that evening, the harbour master had told him that the automated light had worked perfectly the whole time. It had turned, it had flashed its pattern, and it had done exactly what it was built to do. The light could warn a boat away from the rocks, but it could not notice that a boat was in trouble. Only a person could do that, and only if a person was there to look.
|
||||
|
||||
People in the town sometimes talk about that rule now as though it had been a clever piece of planning, a deliberate safeguard against the limits of machines. Tomas does not think it was anything of the kind. He thinks it began because somebody missed the old keeper and could not quite bring themselves to stop going out to the tower, and that it continued because nobody wanted to be the one to end it. Habits are like that. They outlast their reasons, and every so often, without anyone planning it, they find a new one.
|
||||
|
||||
He is twenty-six now and works as an engineer on the offshore wind farm that you can see from the top of the lighthouse on a clear day: two hundred white turbines standing in rows on the horizon, each one watched by sensors that report vibration, temperature and blade pitch to a control room in another country. The systems are very good. They catch almost everything. He still goes out to the tower on Thursdays when he is home, climbs the steps, and looks.
|
||||
|
||||
Ask him why, and he will tell you a story that has nothing to do with lighthouses. In his second year on the wind farm, a monitoring system flagged a slow rise in the temperature of a gearbox on one of the turbines at the far end of the array. The rise was small, well inside the limits, and the software ranked it as low priority. It would have been looked at during the next scheduled visit, six weeks later. A technician on the maintenance boat, passing the turbine on another job, noticed that the nacelle sounded different, a faint grinding note under the usual hum, and asked the skipper to stop. When they opened the gearbox they found a bearing that was a few days from failing. Replacing it cost a morning. Replacing the gearbox after the bearing failed would have cost a month and the price of a small house.
|
||||
|
||||
The technician was not cleverer than the software. She had simply been there, close enough to hear, and curious enough to ask for the boat to stop. The data had shown the same problem; it had just not shown it loudly enough for anyone to care. Tomas thinks about that often. Every system he has worked on has been very good at measuring the things its designers expected to go wrong, and much less good at the things nobody expected. The gap between the two is where people still earn their keep, not by doing the machine's job better than the machine, but by noticing when the job itself has quietly changed.
|
||||
|
||||
So on Thursdays, when he can, he walks out along the pier. The stone is worn smooth in a line down the middle where generations of boots have gone the same way. The iron door still sticks in wet weather. The view from the top has changed more in the last ten years than in the hundred before, and he likes to see it for himself.
|
||||
@@ -0,0 +1,116 @@
|
||||
Strata lässt **[Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)** auf einem normalen PC laufen.
|
||||
Das ist ein großes, kluges KI-Modell, das sonst meist einen Server braucht. Es chattet, schreibt Code, versteht
|
||||
Bilder und arbeitet mit deinen Apps und Coding-Agents zusammen. Nichts verlässt deinen PC.
|
||||
|
||||
## Wie schnell ist es?
|
||||
|
||||
Wir haben es auf zwei ganz normalen Gaming-PCs gemessen. Ein Token ist etwa ¾ eines Wortes.
|
||||
|
||||
- **Schreibt Antworten:** wie schnell die Antwort in einem kurzen Chat erscheint. 60 Tokens pro Sekunde sind
|
||||
schneller, als du lesen kannst.
|
||||
- **Liest deinen Prompt:** wie schnell es aufnimmt, was du schickst (hier ein Dokument, Code oder Chatverlauf mit
|
||||
32K Tokens).
|
||||
|
||||
<table>
|
||||
<tr><th>NVIDIA: RTX 5070 (12 GB), Ryzen 5 7600, 64 GB RAM</th><th>AMD: RX 9070 XT (16 GB), Ryzen 9 3900X, 47 GB RAM</th></tr>
|
||||
<tr><td>
|
||||
|
||||
| Größe | Schreibt Antworten | Liest deinen Prompt |
|
||||
| --- | ---: | ---: |
|
||||
| **Q2_0** | 94 Tokens/s | 2,650 Tokens/s |
|
||||
| **IQ2_XS** | 79 Tokens/s | 2,090 Tokens/s |
|
||||
| **IQ3_XXS** | 62 Tokens/s | 1,750 Tokens/s |
|
||||
| **IQ3_S** | 53 Tokens/s | 1,620 Tokens/s |
|
||||
| **Coder** | 55 Tokens/s | 2,180 Tokens/s |
|
||||
|
||||
</td><td>
|
||||
|
||||
| Größe | Schreibt Antworten | Liest deinen Prompt |
|
||||
| --- | ---: | ---: |
|
||||
| **Q2_0** | 60 Tokens/s | 1,160 Tokens/s |
|
||||
| **IQ2_XS** | 52 Tokens/s | 1,110 Tokens/s |
|
||||
| **Coder** | 44 Tokens/s | 1,420 Tokens/s |
|
||||
|
||||
</td></tr>
|
||||
</table>
|
||||
|
||||
NVIDIA: Q2_0 mit Engine 0.1.36, die anderen Zeilen mit 0.1.26 (4K Antworten, 32K Prompts). Die vollständigen
|
||||
Tabellen stehen in [DETAILS.md](docs/DETAILS.md#speed-measured). Eine Karte mit mehr VRAM ist schneller: Eine
|
||||
RTX 3090 (24 GB) sollte etwa 100-140 Tokens pro Sekunde schreiben. Lange Chats un
|
||||
|
||||
Strata fait tourner **[Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)** sur un PC normal. C'est
|
||||
un grand modèle d'IA, très capable, qui demande d'habitude un serveur. Il discute, écrit du code, lit des images et
|
||||
fonctionne avec vos applications et vos agents de code. Rien ne quitte votre PC.
|
||||
|
||||
## Quelle est sa vitesse ?
|
||||
|
||||
Nous l'avons mesurée sur deux PC de jeu ordinaires. Un token correspond à environ ¾ d'un mot.
|
||||
|
||||
- **Écrit les réponses :** la vitesse à laquelle la réponse s'affiche dans une courte discussion. 60 tokens par seconde, c'est plus rapide que votre lecture.
|
||||
- **Lit votre prompt :** la vitesse à laquelle il absorbe ce que vous envoyez (ici un document, du code ou un historique de discussion de 32K tokens).
|
||||
|
||||
<table>
|
||||
<tr><th>NVIDIA : RTX 5070 (12 Go), Ryzen 5 7600, 64 Go de RAM</th><th>AMD : RX 9070 XT (16 Go), Ryzen 9 3900X, 47 Go de RAM</th></tr>
|
||||
<tr><td>
|
||||
|
||||
| Taille | Écrit les réponses | Lit votre prompt |
|
||||
| --- | ---: | ---: |
|
||||
| **Q2_0** | 94 tokens/s | 2,650 tokens/s |
|
||||
| **IQ2_XS** | 79 tokens/s | 2,090 tokens/s |
|
||||
| **IQ3_XXS** | 62 tokens/s | 1,750 tokens/s |
|
||||
| **IQ3_S** | 53 tokens/s | 1,620 tokens/s |
|
||||
| **Coder** | 55 tokens/s | 2,180 tokens/s |
|
||||
|
||||
</td><td>
|
||||
|
||||
| Taille | Écrit les réponses | Lit votre prompt |
|
||||
| --- | ---: | ---: |
|
||||
| **Q2_0** | 60 tokens/s | 1,160 tokens/s |
|
||||
| **IQ2_XS** | 52 tokens/s | 1,110 tokens/s |
|
||||
| **Coder** | 44 tokens/s | 1,420 tokens/s |
|
||||
|
||||
</td></tr>
|
||||
</table>
|
||||
|
||||
NVIDIA : Q2_0 avec le moteur 0.1.36, les autres lignes ave
|
||||
|
||||
Strata を使うと、**[Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)** を一般的な PC で動かせます。
|
||||
通常はサーバーを必要とする大規模で高性能な AI モデルで、チャットやコードの生成、画像の読み取りができます。
|
||||
アプリやコーディングエージェントとも連携でき、データは PC の外に送信されません。
|
||||
|
||||
## どのくらい速い?
|
||||
|
||||
一般的なゲーミング PC 2 台で速度を測定しました。英語の場合、1 トークンはおよそ ¾ 語に相当します。
|
||||
|
||||
- **生成速度:** 短いチャットで回答を生成する速度です。毎秒 60 トークンなら、人が読むよりも速く文章が表示されます。
|
||||
- **プロンプトの読み込み:** 入力した内容を読み込む速度です。ここでは、文書やコード、チャット履歴など 32K トークン分を読み込ませています。
|
||||
|
||||
<table>
|
||||
<tr><th>NVIDIA: RTX 5070 (12 GB), Ryzen 5 7600, 64 GB RAM</th><th>AMD: RX 9070 XT (16 GB), Ryzen 9 3900X, 47 GB RAM</th></tr>
|
||||
<tr><td>
|
||||
|
||||
| モデルサイズ | 生成速度 | プロンプトの読み込み |
|
||||
| --- | ---: | ---: |
|
||||
| **Q2_0** | 94 tokens/s | 2,650 tokens/s |
|
||||
| **IQ2_XS** | 79 tokens/s | 2,090 tokens/s |
|
||||
|
|
||||
|
||||
Strata 能在普通电脑上运行 **[Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)**。这是一个又大又聪明的
|
||||
AI 模型,通常要用服务器才能跑。它能聊天、写代码、看图片,还能配合你的应用和编程智能体一起工作。所有数据都留在你的电脑上。
|
||||
|
||||
## 速度有多快?
|
||||
|
||||
我们在两台普通的游戏电脑上做了测试。一个 token 大约相当于 ¾ 个英文单词。
|
||||
|
||||
- **写回答:** 短对话中回复出现的速度。每秒 60 个 token 已经比你的阅读速度还快。
|
||||
- **读提示:** 读入你发送内容的速度(这里是一份 32K token 的文档、代码或聊天记录)。
|
||||
|
||||
<table>
|
||||
<tr><th>NVIDIA:RTX 5070(12 GB)、Ryzen 5 7600、64 GB 内存</th><th>AMD:RX 9070 XT(16 GB)、Ryzen 9 3900X、47 GB 内存</th></tr>
|
||||
<tr><td>
|
||||
|
||||
| 规格 | 写回答 | 读提示 |
|
||||
| --- | ---: | ---: |
|
||||
| **Q2_0** | 94 tokens/s | 2,650 tokens/s |
|
||||
| **IQ2_XS** | 79 tokens/s | 2,090 tokens/s |
|
||||
| **IQ3_XXS**
|
||||
@@ -0,0 +1 @@
|
||||
{"version": "v1", "seg_tokens": 1000, "segments": [{"name": "code", "ids": [12237, 85286, 54802, 19913, 343, 18, 4108, 6396, 471, 874, 50285, 980, 11, 874, 50285, 1644, 2195, 88, 13, 271, 34447, 1521, 279, 1510, 13985, 1644, 63, 5187, 1828, 6129, 4021, 1724, 411, 35426, 25, 1141, 1510, 21563, 2581, 42750, 1954, 900, 63, 198, 8746, 682, 874, 4314, 364, 913, 220, 19, 17, 27718, 48, 17, 62, 15, 63, 681, 864, 369, 24733, 1056, 279, 6522, 13, 2844, 369, 4924, 264, 387, 15, 782, 21, 198, 64919, 471, 279, 3443, 411, 4560, 369, 26208, 364, 369, 8047, 314, 279, 5129, 5224, 286, 13, 271, 1919, 369, 279, 5604, 7873, 364, 1510, 3431, 53683, 20123, 14, 63, 318, 77646, 16137, 16, 20, 25, 328, 21563, 19913, 343, 18, 6396, 318, 76, 2117, 11, 198, 2083, 50285, 980, 23285, 61406, 1049, 68434, 279, 4108, 1132, 26, 15167, 795, 369, 2496, 1301, 13, 198, 12237, 198, 1445, 1259, 20409, 548, 1120, 31144, 271, 464, 795, 8588, 198, 464, 51372, 198, 464, 1968, 198, 1445, 18904, 1120, 5586, 271, 21563, 19913, 47540, 283, 220, 15, 87, 19, 21, 20, 20, 19, 22, 19, 22, 220, 653, 328, 21563, 19913, 1, 2545, 12692, 1068, 271, 2, 50285, 980, 1756, 2663, 13, 220, 19, 17, 283, 1167, 17, 62, 15, 11, 279, 34100, 48, 12, 7146, 46, 69764, 17830, 517, 10845, 11, 26334, 494, 50285, 1644, 2195, 88, 430, 314, 220, 15, 13, 16, 24, 13, 198, 21563, 2581, 24973, 25, 6249, 18078, 11, 592, 60, 283, 313, 198, 262, 220, 15, 25, 328, 37, 18, 17, 487, 220, 16, 25, 328, 37, 16, 21, 487, 220, 17, 25, 328, 48, 19, 62, 15, 487, 220, 18, 25, 328, 48, 19, 62, 16, 487, 220, 19, 25, 328, 48, 19, 62, 17, 487, 220, 20, 25, 328, 48, 19, 62, 18, 487, 220, 21, 25, 328, 48, 20, 62, 15, 487, 220, 22, 25, 328, 48, 20, 62, 16, 487, 198, 262, 220, 23, 25, 328, 48, 23, 62, 15, 487, 220, 24, 25, 328, 48, 23, 62, 16, 487, 220, 16, 15, 25, 328, 48, 17, 9802, 487, 220, 16, 16, 25, 328, 48, 18, 9802, 487, 220, 16, 17, 25, 328, 48, 19, 9802, 487, 220, 16, 18, 25, 328, 48, 20, 9802, 487, 220, 16, 19, 25, 328, 48, 21, 9802, 487, 198, 262, 220, 16, 20, 25, 328, 48, 23, 9802, 487, 220, 16, 21, 25, 328, 59865, 17, 62, 5955, 50, 487, 220, 16, 22, 25, 328, 59865, 17, 6645, 50, 487, 220, 16, 23, 25, 328, 59865, 18, 62, 5955, 50, 487, 220, 16, 24, 25, 328, 59865, 16, 1063, 487, 220, 17, 15, 25, 328, 59865, 19, 1548, 43, 487, 198, 262, 220, 17, 16, 25, 328, 59865, 18, 1063, 487, 220, 17, 17, 25, 328, 59865, 17, 1063, 487, 220, 17, 18, 25, 328, 59865, 19, 6645, 50, 487, 220, 17, 19, 25, 328, 40, 23, 487, 220, 17, 20, 25, 328, 40, 16, 21, 487, 220, 17, 21, 25, 328, 40, 18, 17, 487, 220, 17, 22, 25, 328, 40, 21, 19, 487, 198, 262, 220, 17, 23, 25, 328, 37, 21, 19, 487, 220, 17, 24, 25, 328, 59865, 16, 1203, 487, 220, 18, 15, 25, 328, 19278, 16, 21, 487, 220, 18, 16, 25, 328, 48, 19, 62, 15, 62, 19, 62, 19, 487, 220, 18, 17, 25, 328, 48, 19, 62, 15, 62, 19, 62, 23, 487, 220, 18, 18, 25, 328, 48, 19, 62, 15, 62, 23, 62, 23, 487, 198, 262, 220, 18, 19, 25, 328, 51, 48, 16, 62, 15, 487, 220, 18, 20, 25, 328, 51, 48, 17, 62, 15, 487, 220, 18, 21, 25, 328, 59865, 19, 1548, 43, 62, 19, 62, 19, 487, 220, 18, 22, 25, 328, 59865, 19, 1548, 43, 62, 19, 62, 23, 487, 220, 18, 23, 25, 328, 59865, 19, 1548, 43, 62, 23, 62, 23, 487, 198, 262, 220, 18, 24, 25, 328, 28463, 11361, 19, 487, 220, 19, 15, 25, 328, 35125, 11361, 19, 487, 220, 19, 16, 25, 328, 48, 19, 62, 15, 62, 23, 62, 23, 487, 220, 19, 17, 25, 328, 48, 17, 62, 15, 487, 198, 92, 271, 2, 54802, 19913, 10836, 869, 913, 13746, 198, 21563, 19913, 57818, 283, 313, 198, 262, 220, 15, 25, 3376, 84, 23, 487, 220, 16, 681, 220, 16, 25, 3376, 72, 23, 487, 220, 16, 681, 220, 17, 25, 3376, 84, 16, 21, 487, 220, 17, 681, 220, 18, 25, 3376, 72, 16, 21, 487, 220, 17, 681, 220, 19, 25, 3376, 84, 18, 17, 487, 220, 19, 681, 220, 20, 25, 3376, 72, 18, 17, 487, 220, 19, 681, 198, 262, 220, 21, 25, 3376, 69, 18, 17, 487, 220, 19, 681, 220, 22, 25, 3376, 2554, 487, 220, 16, 681, 220, 23, 25, 3376, 889, 487, 2168, 681, 220, 24, 25, 3376, 1595, 487, 2168, 681, 198, 262, 220, 16, 15, 25, 3376, 84, 21, 19, 487, 220, 23, 681, 220, 16, 16, 25, 3376, 72, 21, 19, 487, 220, 23, 681, 220, 16, 17, 25, 3376, 69, 21, 19, 487, 220, 23, 681, 198, 92, 271, 2, 50285, 980, 2424, 16547, 364, 279, 3107, 56373, 411, 1558, 5533, 25, 318, 4425, 5255, 11, 5639, 791, 2424, 8, 198, 2, 1061, 369, 1092, 3520, 264, 791, 2308, 3677, 4763, 1698, 1716, 470, 11, 321, 424, 369, 279, 4954, 279, 61369, 4191, 13, 198, 38637, 57038, 83072, 25, 6249, 16793, 11, 13992, 18078, 11, 514, 4891, 283, 313, 198, 262, 328, 37, 18, 17, 763, 318, 16, 11, 220, 19, 681, 328, 37, 16, 21, 763, 318, 16, 11, 220, 17, 681, 328, 19278, 16, 21, 763, 318, 16, 11, 220, 17, 681, 328, 37, 21, 19, 763, 318, 16, 11, 220, 23, 681, 198, 262, 328, 48, 19, 62, 15, 763, 318, 18, 17, 11, 220, 16, 23, 681, 328, 48, 19, 62, 16, 763, 318, 18, 17, 11, 220, 17, 15, 681, 328, 48, 20, 62, 15, 763, 318, 18, 17, 11, 220, 17, 17, 681, 328, 48]}, {"name": "docs", "ids": [12, 2972, 48213, 318, 18232, 1354, 188912, 6326, 321, 24167, 6738, 6311, 382, 11, 27Line truncated
|
||||
@@ -0,0 +1,81 @@
|
||||
# Unsloth's K-quants and Q8_0: formats, kernels and quality
|
||||
|
||||
This page covers Unsloth's files of the model ([unsloth/Qwen3.8-Flash-Next-GGUF](https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF),
|
||||
revision `38bb39e`; the repository's head `766911a` has the same files, byte for byte): what each file stores in
|
||||
each layer, which of Strata's kernels run those formats on each kind of hardware, and how close each file comes to
|
||||
the Q8_0 reference. Setup and the per-file details: [UD-Q4_K_XL](UNSLOTH_Q4.md), [UD-Q6_K_XL](UNSLOTH_Q6.md),
|
||||
[MODELS.md](MODELS.md).
|
||||
|
||||
## What each file stores
|
||||
|
||||
Read from the GGUF headers alone with `tools/quant_formats.py --hf unsloth/Qwen3.8-Flash-Next-GGUF 38bb39ee... <dir>`
|
||||
(HTTP range requests, nothing else is downloaded; on local shards: `tools/quant_formats.py <shard glob>`).
|
||||
|
||||
The routed experts (gate, up, down; 512 per layer, 10 used per token) are where the files differ:
|
||||
|
||||
| File | Download | Routed gate / up | Routed down | Routed experts | Per token (10 experts x 48 layers) |
|
||||
|---|---:|---|---|---:|---:|
|
||||
| UD-IQ4_XS | 93.7 GB | IQ3_S (IQ4_XS in layer 2) | IQ4_NL (Q8_0 in layers 2, 4, 30, 46, 47) | 55.4 GiB | 1.16 GB |
|
||||
| UD-Q4_K_XL | 111.3 GB | Q4_K (Q5_K in layer 2) | Q5_1 (Q8_0 in layers 2, 4, 30, 46, 47) | 71.7 GiB | 1.50 GB |
|
||||
| UD-Q5_K_XL | 158.3 GB | Q5_K (Q6_K in layer 2) | Q8_0 | 91.6 GiB | 1.92 GB |
|
||||
| UD-Q6_K_XL | 169.2 GB | Q6_K (Q8_0 in layer 2) | Q8_0 | 101.7 GiB | 2.13 GB |
|
||||
| Q8_0 | 188.2 GB | Q8_0 | Q8_0 | 119.5 GiB | 2.51 GB |
|
||||
|
||||
Everything else is the same in all five: the attention, SSM, hyper-connection and shared-expert projections, the
|
||||
PLE key/value and the token embedding are Q8_0 (the small vectors, norms and the router F32; the QSA indexer BF16),
|
||||
the output head is Q8_0 (Q6_K in UD-IQ4_XS). The PLE table (`per_layer_token_embd`) is IQ4_NL (26.8 GiB) in UD-IQ4_XS
|
||||
and UD-Q4_K_XL and Q8_0 (50.7 GiB) in UD-Q5_K_XL, UD-Q6_K_XL and Q8_0. The dense side the GPU reads once per verify
|
||||
window is about 4.8 GB in every file.
|
||||
|
||||
UD-Q5_K_XL, UD-Q6_K_XL and Q8_0 share their shards 2 (the output head) and 3 (the PLE table) byte for byte (the same
|
||||
SHA-256), so a PC that has one of them can link those two shards instead of downloading them again.
|
||||
|
||||
## Kernels per format and backend
|
||||
|
||||
| Format (role) | CUDA decode (grouped experts) | CUDA prompt | CPU pool | AMD (HIP) decode | AMD prompt | Intel (SYCL) decode | Intel prompt |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| Q4_K (gate/up) | yes | FP16 path; MMQ with `STRATA_MMQ_KQ=1` | ggml AVX2 dot; multi-token AVX2 (`STRATA_KQ256=1`) | yes (CUDA layout; `STRATA_EXPERT_V2K=1` bitwise) | FP16 path; MMQ with `STRATA_MMQ_KQ=1`; gfx11 fused (`STRATA_PF_FUSED_KQ=1`) | kernels built, not run with these files | FP16 path |
|
||||
| Q5_K (gate/up) | yes | as Q4_K | ggml AVX2 dot | as Q4_K | as Q4_K | kernels built, not run with these files | FP16 path |
|
||||
| Q6_K (gate/up) | yes (since this change; was `-DSTRATA_Q6K_EXPERTS=ON`) | FP16 path; MMQ with `STRATA_MMQ_KQ=1` | ggml AVX2 dot | yes (CUDA layout) | FP16 path; MMQ with `STRATA_MMQ_KQ=1` | kernels built, not run with these files | FP16 path |
|
||||
| Q5_1 (down) | yes | as Q4_K | ggml AVX2 dot; multi-token AVX2 (`STRATA_KQ256=1`) | yes (CUDA layout; V2K) | as Q4_K | kernels built, not run with these files | FP16 path |
|
||||
| Q8_0 (gate/up, down) | yes | MMQ | ggml AVX2 dot; multi-token AVX2 down (`STRATA_KQ256=1`) | yes (CUDA layout; V2K down) | MMQ | kernels built, not run with these files | FP16 path |
|
||||
|
||||
- "FP16 path": the prompt's experts dequantized to FP16 and multiplied by the BLAS library. It works for every format
|
||||
above but reads each expert as ~10 MB of FP16.
|
||||
- **Formats cost nothing unless used.** The engine loads every kernel of its own binary when it starts (so that no
|
||||
kernel needs VRAM later, mid-prompt), which is why kernels for formats a model does not have used to take expert
|
||||
slots from every model. The Q6_K expert kernels are now part of every build: one more instance per grouped kernel,
|
||||
+19 KB of sm_60 code, and the expert-cache slot counts measured unchanged (IQ3_XXS: 6,028 slots on a P100, 15,878
|
||||
and 1,980 on an R9700). The K-quant MMQ prompt kernels (Q4_K, Q5_K, Q5_1, Q6_K: ~3.8 MB of sm_60 code, 3 IQ3_XXS
|
||||
slots on the P100 when they were in the engine) are on CUDA a library of their own next to the engine
|
||||
(`libstrata_kq.so` / `strata_kq.dll`), opened only for a model with these experts and `STRATA_MMQ_KQ=1`; without the
|
||||
file those experts take the FP16 prompt path. On AMD a code object loads on first use, so they stay in the engine.
|
||||
- `STRATA_MMQ_KQ=1` is opt-in because MMQ rounds the prompt's products differently from the FP16 path (the output
|
||||
differs at the rounding level); its speed and KL are measured before it becomes a default.
|
||||
|
||||
## Quality: the yardstick
|
||||
|
||||
`tools/quant_quality.py` scores a quant against Q8_0 on one fixed text set (`data/quant_quality/v1`: code, docs,
|
||||
English prose, German/French/Japanese/Chinese, an agent transcript; 5 x 1,000 tokens in `set.ids.json`). Every token
|
||||
is read through the decode windows (teacher-forced) with the experts on the CPU (one VRAM slot), no expert
|
||||
adaptation, no PCIe share, no route tail skip, FP16 K/V; per position the engine writes the log-probability of the
|
||||
text's next token and its 64 most likely tokens (`STRATA_LOGPOS`, `STRATA_LOGPOS_TOPK=64`). Top-1 agreement: the
|
||||
same most likely token as Q8_0. KL: KL(Q8_0 || quant) over Q8_0's 64 most likely tokens.
|
||||
|
||||
```sh
|
||||
python tools/quant_quality.py run --config strata-<quant>.json --out <quant>.tsv
|
||||
python tools/quant_quality.py compare q8_0.tsv <quant>.tsv --segments
|
||||
```
|
||||
|
||||
Measured on the AMD box (EPYC 7452, R9700, HIP, engine at 0601072d; 4,995 positions; Q8_0 against itself in a second
|
||||
run: byte-identical rows):
|
||||
|
||||
| Quant | Same top token as Q8_0 | Mean KL | KL p99 | Perplexity (Q8_0: 4.052) |
|
||||
|---|---:|---:|---:|---:|
|
||||
| UD-Q5_K_XL | 94.55% | 0.038 | 0.636 | 4.024 |
|
||||
| UD-Q4_K_XL | 93.09% | 0.056 | 0.829 | 4.068 |
|
||||
| IQ3_S | 87.69% | 0.144 | 1.975 | 4.097 |
|
||||
| IQ3_XXS | 84.46% | 0.202 | 2.433 | 4.119 |
|
||||
| Q2_0 | 80.60% | 0.315 | 3.643 | 4.475 |
|
||||
|
||||
UD-Q6_K_XL and UD-IQ4_XS follow.
|
||||
+6
-5
@@ -177,11 +177,12 @@ also fails, the warning preserves both the GPU allocation or mapping error and t
|
||||
flight when the experts are read from the GGUF in place (`STRATA_STAGER_THREADS` / `STRATA_STAGER_RING` override
|
||||
it; 4 and 16 before, still the default for every other model). Between the chunks, the 28.8 GB PLE table's rows
|
||||
take ~5 s per chunk.
|
||||
- An engine compiled with `-DSTRATA_MMQ_KQUANTS=ON` multiplies the Q4_K / Q5_K / Q5_1 experts of a prompt with
|
||||
llama.cpp's MMQ kernels (as the other models' formats always are) instead of dequantizing them to FP16: 4x less GPU
|
||||
time for those products, but on this PC the prompt waits for the SSD either way (29 s per 4K chunk with or
|
||||
without). Off in the released engine: it loads every kernel at start, and these took 1-3 expert slots of VRAM from
|
||||
every model.
|
||||
- With `STRATA_MMQ_KQ=1` the engine multiplies the Q4_K / Q5_K / Q5_1 experts of a prompt with llama.cpp's MMQ
|
||||
kernels (as the other models' formats always are) instead of dequantizing them to FP16: 4x less GPU time for those
|
||||
products, but on this PC the prompt waits for the SSD either way (29 s per 4K chunk with or without). Opt-in: it
|
||||
rounds differently from the FP16 path. On CUDA these kernels are a library next to the engine (`libstrata_kq.so` /
|
||||
`strata_kq.dll`), opened only then, so they take no VRAM from other models ([QUANTS.md](QUANTS.md)); before, they were
|
||||
the build option `-DSTRATA_MMQ_KQUANTS=ON` and took 1-3 expert slots from every model.
|
||||
- The speed varies from run to run (6.7-8.6 tok/s at 40 GiB for the same prompt), with what the OS file cache holds.
|
||||
- For comparison, IQ3_S (all its experts in RAM) writes ~53 tok/s on the same PC ([the speed tables](DETAILS.md#speed-measured)).
|
||||
- Where the time goes (`--stats` on the command line): at 40 GiB about 550-750 ms of each verify round (3.5 tokens) is
|
||||
|
||||
+5
-5
@@ -6,10 +6,10 @@ same model the other packs use:
|
||||
Build it for engine 0.1.38 or newer (earlier engines read `per_layer_token_embd.weight` in IQ4_NL, Q5_0 or FP8 only,
|
||||
below). UD-Q4_K_XL's manual workflow asks nothing of setup, and neither does this one.
|
||||
|
||||
> **0.1.40 status.** The Q6_K gate/up kernels are an opt-in build (`-DSTRATA_Q6K_EXPERTS=ON`, plus `-DSTRATA_MMQ_KQUANTS=ON`
|
||||
> for the prompt kernels): every grouped-kernel instance is loaded at start and would cost other models expert slots. The
|
||||
> Q8_0 PLE table reader is not in this release (it comes with the PLE format series, PR #651); until then this file does
|
||||
> not load. The parity programs below have not been run on a GPU yet.
|
||||
> **Status (MODEL-UPDATE Phase 1).** The Q6_K gate/up kernels are part of every build now (they were the opt-in
|
||||
> `-DSTRATA_Q6K_EXPERTS=ON`): measured to leave other models' expert-cache slots unchanged ([QUANTS.md](QUANTS.md)). The
|
||||
> MMQ prompt kernels for Q6_K come with the K-quant library and `STRATA_MMQ_KQ=1`; without it the prompt takes the FP16
|
||||
> path. The file runs on the standard engine (AMD R9700: the quality yardstick in [QUANTS.md](QUANTS.md)).
|
||||
|
||||
## What is in the file
|
||||
|
||||
@@ -108,7 +108,7 @@ it (the PLE Q8_0 reader is the other half):
|
||||
- **Decode windows:** the grouped expert kernels (`native_expert_grouped`) take gate/up Q6_K — a pinned copy of
|
||||
llama.cpp's `vec_dot_q6_K_q8_1` behind `Fmt<14>`, and the dequantizer (`dequantize_q6_K` folded onto the kernel's
|
||||
32 threads). Per-token MMVQ (`native_mmvq`) already had Q6_K.
|
||||
- **The prompt path:** llama.cpp's MMQ prompt kernels now instantiate Q6_K (`STRATA_MMQ_KQUANTS=ON` builds
|
||||
- **The prompt path:** llama.cpp's MMQ prompt kernels instantiate Q6_K (the K-quant library, `STRATA_MMQ_KQ=1`; it builds
|
||||
`template-instances/mmq-instance-q6_k.cu` alongside q4_k/q5_k/q5_1; `moe_mmq` accepts and dispatches it).
|
||||
- **The gates:** `native_expert_supported` took Q6_K/Q8_0 pairs (gate/up Q8_0 as in layer 2 was already in the
|
||||
lists) — the engine previously refused the whole pack with "no GPU kernels for".
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
// include/strata/prefill/mmq_kq_abi.hpp - the interface between the engine (src/prefill/moe_mmq.cu) and strata_kq, the
|
||||
// shared library with the K-quant MMQ prompt kernels (src/prefill/mmq_kq_lib.cu). Bump the version when a function's
|
||||
// meaning changes; the argument block (ggml's mmq_args) is checked by its size.
|
||||
#pragma once
|
||||
|
||||
#define STRATA_KQ_ABI_VERSION 1
|
||||
|
||||
#if defined(_WIN32)
|
||||
#define STRATA_KQ_LIB_NAME "strata_kq.dll"
|
||||
#else
|
||||
#define STRATA_KQ_LIB_NAME "libstrata_kq.so"
|
||||
#endif
|
||||
|
||||
extern "C" {
|
||||
typedef int (*strata_kq_abi_fn)();
|
||||
typedef int (*strata_kq_init_fn)(int device);
|
||||
typedef int (*strata_kq_run_fn)(int device, int ggml_type, const void* mmq_args, void* stream);
|
||||
}
|
||||
|
||||
// the engine's side (src/prefill/mmq_kq_loader.cpp)
|
||||
namespace strata::prefill::mmq::kq {
|
||||
/// STRATA_MMQ_KQ=1: the K-quant experts' prompt products through MMQ (opt-in: other rounding than the FP16 path).
|
||||
bool wanted();
|
||||
/// wanted() and the library is open and started on every GPU (the first call opens it and says what happened).
|
||||
bool available();
|
||||
/// One product on the current GPU: 0 = launched, else an error (-1: no library or not this type).
|
||||
int run(int ggml_type, const void* mmq_args, void* stream);
|
||||
/// sizeof(mmq_args) on the engine's side (moe_mmq.cu), checked against the library's.
|
||||
int abi_args_size();
|
||||
} // namespace strata::prefill::mmq::kq
|
||||
@@ -213,15 +213,6 @@ MODELS = {
|
||||
# the Coder release: 256 of the 512 experts kept (the ones code, tools and vision use), IQ2_S-IQ4_XS like IQ3_S
|
||||
"IQ1_M": {"about": "the Coder's only size: half the experts, stored like IQ3_S (3.5 bits)", "download_gb": 58.4,
|
||||
"ram_gb": 32, "arena_gb": 23.4, "families": ("coder",)},
|
||||
# EXPERIMENTAL (docs/UNSLOTH_Q4.md): Unsloth's 4-bit file; its 77 GB of experts do not fit a 64 GB PC, so the engine
|
||||
# keeps a RAM budget of them (--resident-budget-gib, chosen below) and reads the rest from the GGUF on the SSD
|
||||
"UD-Q4_K_XL": {"about": "4-bit (Unsloth Dynamic), EXPERIMENTAL: the best quality, but most experts come from the "
|
||||
"SSD on a 64 GB PC (7-8.5 tokens/s measured)", "download_gb": 111.3, "ram_gb": 48,
|
||||
"arena_gb": 77.0, "families": ("unsloth",), "budget": True, "nvidia_only": True,
|
||||
"experimental": True,
|
||||
# #967: images are allowed (the same base model and image encoder as UD-IQ4_XS), with a warning:
|
||||
# reported working by hand (#967, #971), not tested by us on this file
|
||||
"vision": True, "vision_untested": True},
|
||||
# #621: Unsloth's UD-IQ4_XS - IQ3_S gate/up experts with IQ4_NL (43 layers) or Q8_0 (5) downs, the dense side as
|
||||
# UD-Q4_K_XL's; three shards. A regular choice from 0.1.39 (no longer experimental). Its 59.5 GB of experts: a
|
||||
# RAM budget of them, like UD-Q4_K_XL, but far fewer read from the SSD on a 64 GB PC and none from ~80 GB of RAM.
|
||||
@@ -231,6 +222,32 @@ MODELS = {
|
||||
"download_gb": 93.7, "ram_gb": 48, "arena_gb": 59.5, "families": ("unsloth",), "budget": True,
|
||||
"shards": 3, "file": "Qwen3.8-Flash-Next-{q}-0000{i}-of-00003.gguf", "engine": (0, 1, 38),
|
||||
"vision": True},
|
||||
# Unsloth's 4-bit file (docs/UNSLOTH_Q4.md); experimental until MODEL-UPDATE Phase 2. Its 77 GB of experts stay in
|
||||
# RAM from ~94 GB of RAM (unsloth_budget); on a 64 GB PC the engine keeps a RAM budget of them
|
||||
# (--resident-budget-gib, chosen below) and reads the rest from the GGUF on the SSD. It runs on AMD too (R9700:
|
||||
# the quality yardstick and the decode/prompt numbers in docs/QUANTS.md), so it is no longer NVIDIA-only (#429).
|
||||
"UD-Q4_K_XL": {"about": "4-bit (Unsloth Dynamic): K-quant experts, between UD-IQ4_XS and UD-Q5_K_XL in quality",
|
||||
"download_gb": 111.3, "ram_gb": 48, "arena_gb": 77.0, "families": ("unsloth",), "budget": True,
|
||||
# #967: images are allowed (the same base model and image encoder as UD-IQ4_XS), with a warning:
|
||||
# reported working by hand (#967, #971), not tested by us on this file
|
||||
"vision": True, "vision_untested": True},
|
||||
# MODEL-UPDATE: Unsloth's larger files (docs/QUANTS.md). The same GGUF-in-place mode: every expert in RAM where it
|
||||
# fits with UNSLOTH_RESIDENT_BESIDE_GB more (unsloth_budget), else a RAM budget of them and the rest read from the
|
||||
# SSD while it answers - so "ram_gb" is the all-in-RAM need, and below it setup asks first (default no). Their
|
||||
# shards 2 (the head) and 3 (the 54 GB Q8_0 PLE table) are the same bytes in all three files. UD-Q5_K_XL and
|
||||
# UD-Q6_K_XL need the Q6_K expert kernels every engine has from MODEL-UPDATE Phase 1 on (Q5: layer 2's gate/up).
|
||||
"UD-Q5_K_XL": {"about": "5-bit (Unsloth Dynamic): Q5_K experts with Q8_0 downs, close to Q8_0 in quality",
|
||||
"download_gb": 158.3, "ram_gb": 108, "arena_gb": 98.4, "families": ("unsloth",), "budget": True,
|
||||
"shards": 6, "file": "Qwen3.8-Flash-Next-{q}-0000{i}-of-00006.gguf", "engine": (0, 1, 44),
|
||||
"vision": True},
|
||||
"UD-Q6_K_XL": {"about": "6-bit (Unsloth Dynamic): Q6_K experts with Q8_0 downs",
|
||||
"download_gb": 169.2, "ram_gb": 118, "arena_gb": 109.2, "families": ("unsloth",), "budget": True,
|
||||
"shards": 6, "file": "Qwen3.8-Flash-Next-{q}-0000{i}-of-00006.gguf", "engine": (0, 1, 44),
|
||||
"vision": True},
|
||||
"Q8_0": {"about": "8-bit, the reference quality (every expert Q8_0); for a 192 GB PC",
|
||||
"download_gb": 188.2, "ram_gb": 136, "arena_gb": 128.3, "families": ("unsloth",), "budget": True,
|
||||
"shards": 6, "file": "Qwen3.8-Flash-Next-{q}-0000{i}-of-00006.gguf", "engine": (0, 1, 38),
|
||||
"vision": True},
|
||||
}
|
||||
# The experimental Unsloth file's four shards at the pinned revision: name -> (bytes, sha256), checked after the
|
||||
# download (setup trusts no other model file by name and size alone either: check_shards reads their directories).
|
||||
@@ -253,8 +270,49 @@ UNSLOTH_IQ4_XS_SHARDS = {
|
||||
"Qwen3.8-Flash-Next-UD-IQ4_XS-00003-of-00003.gguf":
|
||||
(43836407744, "d4634e6d84f0ebb0940be15c90d3790bf6464e3dea3a1cddc567dc0e83ad8833"),
|
||||
}
|
||||
# MODEL-UPDATE: UD-Q5_K_XL, UD-Q6_K_XL and Q8_0 at the same revision (sizes and SHA-256: the Hub's LFS pointers; shards
|
||||
# 2 and 3 are byte-identical across the three)
|
||||
UNSLOTH_BIG_SHARDS = {
|
||||
"Qwen3.8-Flash-Next-UD-Q5_K_XL-00001-of-00006.gguf":
|
||||
(10946618, "610922cdb1afe1094e95d7a3e86b12ee33317ebbf7320ac9344e21b6ae4bb69f"),
|
||||
"Qwen3.8-Flash-Next-UD-Q5_K_XL-00002-of-00006.gguf":
|
||||
(682434912, "494ca4ed3dbf97bc28da88af3890b8877b9032f909812d00c0526a9ca5e91d2e"),
|
||||
"Qwen3.8-Flash-Next-UD-Q5_K_XL-00003-of-00006.gguf":
|
||||
(54400261312, "34efd79a80a1ce540a517a5d56171924b66ce1c38b04c904f17ad6d8ef17cf20"),
|
||||
"Qwen3.8-Flash-Next-UD-Q5_K_XL-00004-of-00006.gguf":
|
||||
(49990245824, "9ee6bbe462e6830864382d629101490625b1c95afa15492b7ad550c7bed2dd13"),
|
||||
"Qwen3.8-Flash-Next-UD-Q5_K_XL-00005-of-00006.gguf":
|
||||
(49882416192, "0b2437f661f584030cb5aeb8fb1bb70f6422518a6746bfcc0304167c7b6b8beb"),
|
||||
"Qwen3.8-Flash-Next-UD-Q5_K_XL-00006-of-00006.gguf":
|
||||
(3320101792, "55dd96c5ad0863b06b6393151b9ad0ac727b8d58a62e02a296ca5d5ddbfee4a3"),
|
||||
"Qwen3.8-Flash-Next-UD-Q6_K_XL-00001-of-00006.gguf":
|
||||
(10946624, "8bdc6bad55b6699f46f60708829932ff4018d7ac9bd309c388534fa31753bdb7"),
|
||||
"Qwen3.8-Flash-Next-UD-Q6_K_XL-00002-of-00006.gguf":
|
||||
(682434912, "494ca4ed3dbf97bc28da88af3890b8877b9032f909812d00c0526a9ca5e91d2e"),
|
||||
"Qwen3.8-Flash-Next-UD-Q6_K_XL-00003-of-00006.gguf":
|
||||
(54400261312, "34efd79a80a1ce540a517a5d56171924b66ce1c38b04c904f17ad6d8ef17cf20"),
|
||||
"Qwen3.8-Flash-Next-UD-Q6_K_XL-00004-of-00006.gguf":
|
||||
(49814108512, "0ea4b599880a5a52fcd9c188ba1443f646c69c96571904ddbd6a79246a01a997"),
|
||||
"Qwen3.8-Flash-Next-UD-Q6_K_XL-00005-of-00006.gguf":
|
||||
(49419317344, "9948e81ae8368144b135a7403d8c0f2cf9a6c2f9f692313865855b2832e696c9"),
|
||||
"Qwen3.8-Flash-Next-UD-Q6_K_XL-00006-of-00006.gguf":
|
||||
(14838313984, "e4ae255234f42b18012f6d6eec5bf615b57479b7e0a0233c47436a321ffeec3f"),
|
||||
"Qwen3.8-Flash-Next-Q8_0-00001-of-00006.gguf":
|
||||
(10946624, "2dabcbb53ca537a7947bc7d20414fd464eeaf4d66d43021b5b2556cc87544ad2"),
|
||||
"Qwen3.8-Flash-Next-Q8_0-00002-of-00006.gguf":
|
||||
(682434912, "494ca4ed3dbf97bc28da88af3890b8877b9032f909812d00c0526a9ca5e91d2e"),
|
||||
"Qwen3.8-Flash-Next-Q8_0-00003-of-00006.gguf":
|
||||
(54400261312, "34efd79a80a1ce540a517a5d56171924b66ce1c38b04c904f17ad6d8ef17cf20"),
|
||||
"Qwen3.8-Flash-Next-Q8_0-00004-of-00006.gguf":
|
||||
(49446841216, "bfa634025fabbd2658bf7694bc80b90e571699c768723f844c934c7ef06c691a"),
|
||||
"Qwen3.8-Flash-Next-Q8_0-00005-of-00006.gguf":
|
||||
(49668930400, "232a8f14cc0fa4262e7efe8593774b136fe40909e39c7a020342ddaa27259a97"),
|
||||
"Qwen3.8-Flash-Next-Q8_0-00006-of-00006.gguf":
|
||||
(34015618784, "538a93bca918064983409a41187ad4c68640f9aced6f29564da8f551bf86d7a5"),
|
||||
}
|
||||
UNSLOTH_ENGINE = (0, 1, 32) # the first engine setup configures for UD-Q4_K_XL (0.1.31 ran it by hand)
|
||||
UNSLOTH_RAM_LEFT_GB = 24 # RAM beside the budget: the OS, the engine, and the file cache the rest is read through
|
||||
UNSLOTH_MIN_RAM_GB = 48 # the RAM-budget mode below which setup says an Unsloth file does not fit (UD-Q4_K_XL's floor)
|
||||
# Contexts past 262144 (the model's trained length) extend it by rope scaling: for the context it will
|
||||
# serve the setup resolves the method (yarn, or one question when interactive) and derives the factor
|
||||
# from the final context (final / 262144, at least 1) itself (below), keeps an explicit
|
||||
@@ -289,15 +347,15 @@ FAMILIES = {
|
||||
"profile": "expert-profile-coder.bin"},
|
||||
# Unsloth's UD-IQ4_XS (three shards, #621; a regular choice from 0.1.39) and the EXPERIMENTAL UD-Q4_K_XL (four)
|
||||
# of the original model (docs/UNSLOTH_Q4.md); "experimental" and "vision" are per model (MODELS)
|
||||
"unsloth": {"title": "Qwen3.8-Flash-Next (Unsloth)", "by": "Unsloth's ~4-bit quantizations",
|
||||
"about": "UD-IQ4_XS: a 94 GB download; with less than ~80 GB of RAM part of its experts are read from "
|
||||
"the SSD (UD-Q4_K_XL, 111 GB: experimental)",
|
||||
"unsloth": {"title": "Qwen3.8-Flash-Next (Unsloth)", "by": "Unsloth's 4- to 8-bit quantizations",
|
||||
"about": "UD-IQ4_XS (94 GB download) to Q8_0 (188 GB): every expert in RAM from ~80 GB (UD-IQ4_XS) "
|
||||
"to ~136 GB (Q8_0) of RAM, else part of them read from the SSD",
|
||||
"hf": hf("unsloth/Qwen3.8-Flash-Next-GGUF") + "{q}/",
|
||||
"file": "Qwen3.8-Flash-Next-{q}-0000{i}-of-00004.gguf", "shards": 4, "tag": "unsloth-",
|
||||
"mmproj_hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF"),
|
||||
"mmproj": "mmproj-Qwen3.8-Flash-Next-BF16.gguf", "name": "qwen3.8-flash-next-unsloth",
|
||||
"vision": False, "pack_args": ["--compat-bf16"],
|
||||
"sha256": {**UNSLOTH_SHARDS, **UNSLOTH_IQ4_XS_SHARDS}},
|
||||
"sha256": {**UNSLOTH_SHARDS, **UNSLOTH_IQ4_XS_SHARDS, **UNSLOTH_BIG_SHARDS}},
|
||||
}
|
||||
MMPROJ = "mmproj-Qwen3.8-Flash-Next-BF16.gguf"
|
||||
# NEW-MODELS-PLAN.md T0: Qwen3.6-35B-A3B (GGUF architecture qwen35moe), Unsloth's GGUFs with the MTP block. Setup knows
|
||||
@@ -332,6 +390,9 @@ VISION = {"gpu": {"max_tokens": 1024, "reserve_mib": 700},
|
||||
"cpu": {"max_tokens": 300, "reserve_mib": 700}}
|
||||
EXE = "strata.exe" if WIN else "strata"
|
||||
VEXE = "strata-vision.exe" if WIN else "strata-vision"
|
||||
# MODEL-UPDATE Phase 1: the K-quant prompt kernels (Unsloth's UD-Q4/Q5/Q6_K_XL experts) are a library next to the CUDA
|
||||
# engine, opened only for those models; an engine without it runs them on the FP16 prompt path
|
||||
KQ_LIB = "strata_kq.dll" if WIN else "libstrata_kq.so"
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ output
|
||||
@@ -1601,9 +1662,8 @@ def gguf_dir_shards(folder: Path, fam: dict, model: str) -> list[Path]:
|
||||
GGUF_QUANT = re.compile(r"(?<![A-Za-z0-9])((?:UD-)?(?:I?Q\d+(?:_[A-Za-z0-9]+)*|BF16|F16|F32))"
|
||||
r"(?=-\d{5}-of-\d{5}\.gguf$|\.gguf$)", re.I)
|
||||
SUPPORTED_GGUFS = ("Strata runs ISTA-DASLab's GSQ-RCO files (Qwen3.8-Flash-Next Q2_0, IQ2_XS, IQ3_XXS, IQ3_S; Swift "
|
||||
"1.5's; the Coder's IQ1_M) and Unsloth's UD-Q4_K_XL and UD-IQ4_XS only: other GGUFs (Unsloth's "
|
||||
"UD-IQ3_XXS or "
|
||||
"UD-Q2_K_XL, K-quants) cannot be used")
|
||||
"1.5's; the Coder's IQ1_M) and Unsloth's UD-IQ4_XS, UD-Q4_K_XL, UD-Q5_K_XL, UD-Q6_K_XL and Q8_0 "
|
||||
"only: other GGUFs (Unsloth's UD-IQ3_XXS or UD-Q2_K_XL, other K-quant files) cannot be used")
|
||||
|
||||
|
||||
def gguf_unsupported(name: str) -> str | None:
|
||||
@@ -1680,6 +1740,23 @@ def resident_budget_gib(model, ram, kv_ram_gb=0.0) -> int:
|
||||
return max(8, min(gib, int(MODELS[model]["arena_gb"] / 1.073741824)))
|
||||
|
||||
|
||||
# MODEL-UPDATE Phase 2: Unsloth's files keep every expert in RAM (a pinned arena, as ISTA's files do) where the experts
|
||||
# and this much more fit the PC's RAM; the RAM budget (--resident-budget-gib: the hottest experts in RAM, the rest read
|
||||
# from the GGUF in place) only below that. The rule and the 16 GiB are sergqwer's fork (sergqwer/strata-nvfp4,
|
||||
# 0.1.42-nvfp4.2, MIT): there, on 128 GB with an RTX 5090, UD-Q4_K_XL decoded at 169 tokens/s and read a 32K prompt in
|
||||
# 4.9 s with every expert in RAM, against 118 tokens/s and 30 s in the budget mode.
|
||||
UNSLOTH_RESIDENT_BESIDE_GB = 16
|
||||
|
||||
|
||||
def unsloth_budget(model, ram, gpu=None, asked=None) -> bool:
|
||||
"""Does setup write the RAM-budget mode (--resident-budget-gib) for this Unsloth file: asked for (--resident-budget-gib
|
||||
N), a unified-memory APU (#1715: there the budget and the GPU's cache are the same RAM, and the all-in-RAM mode was
|
||||
measured on discrete cards only), or its experts with UNSLOTH_RESIDENT_BESIDE_GB beside them do not fit this PC's RAM
|
||||
(GiB, ram_gb()). Else every expert is kept in RAM, as for ISTA's files."""
|
||||
return asked is not None or bool((gpu or {}).get("uma")) or \
|
||||
ram < MODELS[model]["arena_gb"] / 1.073741824 + UNSLOTH_RESIDENT_BESIDE_GB
|
||||
|
||||
|
||||
UMA_EXPERTS = 24576 # the Flash-Next model's experts (48 layers x 512): the most an expert cache can hold
|
||||
|
||||
|
||||
@@ -3454,6 +3531,10 @@ def build_engine(gpu, vision, yes, llama, toolkit=None) -> Path:
|
||||
f"this source is {source_version()}): the installed engine and its stamp are left as they were",
|
||||
"the build folder " + str(bdir) + " may be configured for something else: delete it and run this again")
|
||||
shutil.copy2(bdir / EXE, eng / EXE)
|
||||
if (bdir / KQ_LIB).exists(): # built with it (Phase 1): it goes next to the engine
|
||||
shutil.copy2(bdir / KQ_LIB, eng / KQ_LIB)
|
||||
elif (eng / KQ_LIB).exists(): # an older one of another build would only be refused
|
||||
(eng / KQ_LIB).unlink()
|
||||
if not vision_ok:
|
||||
say(" Compiling the image encoder" + (" with CUDA (10-20 minutes, once) ..." if vision == "gpu" else " ..."))
|
||||
defs = [f"-DLLAMA_DIR={llama}", f"-DSTRATA_VISION_CUDA={'ON' if vision == 'gpu' else 'OFF'}",
|
||||
@@ -5269,16 +5350,21 @@ def main() -> int:
|
||||
any_fits = False
|
||||
for m, d in MODELS.items():
|
||||
verdict = "fits" if ram >= d["ram_gb"] else "tight" if ram >= d["ram_gb"] - 8 else "does not fit"
|
||||
if d.get("budget"):
|
||||
if d.get("budget") and not unsloth_budget(m, ram, gpu): # Phase 2: all of them in RAM
|
||||
verdict = ("EXPERIMENTAL, " if d.get("experimental") else "") + "fits (all of its experts in RAM)"
|
||||
elif d.get("budget"):
|
||||
verdict = (("EXPERIMENTAL, " if d.get("experimental") else "") +
|
||||
f"fits with {resident_budget_gib(m, ram)} GiB of its experts in RAM, the rest "
|
||||
"read from the SSD" if ram >= d["ram_gb"] else "does not fit")
|
||||
if hip: # #429: not run on AMD yet (its prompt kernels are CUDA-only)
|
||||
verdict += " - NVIDIA only so far, untested on AMD"
|
||||
"read from the SSD" if ram >= d["ram_gb"] else
|
||||
f"slow here: {resident_budget_gib(m, ram)} GiB of its "
|
||||
f"{int(d['arena_gb'] / 1.073741824)} GiB of experts in RAM, the rest read from the SSD "
|
||||
"(setup asks first)" if ram >= UNSLOTH_MIN_RAM_GB else "does not fit")
|
||||
elif low_ram_needed(m, ram) and low_ram_fits(m, ram, low_ram_vram(gpu)) and a.low_ram != "off":
|
||||
verdict = (f"fits in the low-RAM mode (the GPU holds ~{100 * low_ram_gpu_share(m, low_ram_vram(gpu)):.0f}% "
|
||||
"of its experts, " + ("the rest stays in RAM)" if low_ram_resident(m, ram, low_ram_vram(gpu))
|
||||
else "the rest is read from the SSD as needed)"))
|
||||
if d.get("budget") and hip and d.get("nvidia_only"): # #429: not run on AMD yet
|
||||
verdict += " - NVIDIA only so far, untested on AMD"
|
||||
any_fits = any_fits or not verdict.startswith("does not fit")
|
||||
say(f" {m:8s} needs ~{d['ram_gb']} GB RAM: {verdict}")
|
||||
if not any_fits:
|
||||
@@ -5321,24 +5407,35 @@ def main() -> int:
|
||||
d = MODELS[m]
|
||||
fit = "" if ram >= d["ram_gb"] else f" <- needs {d['ram_gb']} GB RAM, you have {ram:.0f}"
|
||||
if d.get("budget"):
|
||||
say(f" {i}) {m} {d['about']}; download {d['download_gb']:.0f} GB, keeps ~"
|
||||
f"{resident_budget_gib(m, ram)} GB of its {d['arena_gb']:.0f} GB of experts in RAM{fit}")
|
||||
keeps = (f"~{resident_budget_gib(m, ram)} GB" if unsloth_budget(m, ram, gpu, a.resident_budget_gib)
|
||||
else "all")
|
||||
say(f" {i}) {m} {d['about']}; download {d['download_gb']:.0f} GB, keeps {keeps} of its "
|
||||
f"{d['arena_gb']:.0f} GB of experts in RAM{fit}")
|
||||
continue
|
||||
if low_ram_needed(m, ram) and low_ram_fits(m, ram, low_ram_vram(gpu)) and a.low_ram != "off":
|
||||
fit = (f" <- fits in the low-RAM mode (the GPU holds ~{100 * low_ram_gpu_share(m, low_ram_vram(gpu)):.0f}%, "
|
||||
+ ("the rest in RAM)" if low_ram_resident(m, ram, low_ram_vram(gpu)) else "the rest from the SSD)"))
|
||||
say(f" {i}) {m:8s} {d['about']}; download {d['download_gb']:.0f} GB, uses ~{d['arena_gb']:.0f} GB of RAM{fit}")
|
||||
rec = str(names.index("IQ3_XXS") + 1) if ram >= 60 and "IQ3_XXS" in names else "1"
|
||||
if family == "unsloth": # MODEL-UPDATE: the largest file whose experts all fit in RAM
|
||||
in_ram = [m for m in names if MODELS[m].get("budget") and not MODELS[m].get("experimental")
|
||||
and not unsloth_budget(m, ram, gpu, a.resident_budget_gib)]
|
||||
best = max(in_ram, key=lambda m: MODELS[m]["arena_gb"]) if in_ram else \
|
||||
("UD-IQ4_XS" if "UD-IQ4_XS" in names else names[0])
|
||||
rec = str(names.index(best) + 1)
|
||||
model = a.model or names[int(ask("Which size?", [str(i) for i in range(1, len(names) + 1)], rec, a.yes)) - 1]
|
||||
budget, q4_split = None, False
|
||||
in_budget = bool(MODELS[model].get("budget")) and unsloth_budget(model, ram, gpu, a.resident_budget_gib)
|
||||
if MODELS[model].get("budget"):
|
||||
# Unsloth's UD-Q4_K_XL: a RAM budget of experts, the rest from the GGUF on the SSD - not the low-RAM mode (no
|
||||
# experts.bin: it would be another 77 GB on the disk), and one GPU (the budget mode had no layer split) unless
|
||||
# the RAM holds the GGUFs and 24 GB more: then several, without the budget, if asked for (#498). #642: from
|
||||
# RESIDENT_SPLIT_ENGINE several GPUs, when asked for, keep the budget (unsloth_together)
|
||||
# Unsloth's files: every expert in RAM where they fit with UNSLOTH_RESIDENT_BESIDE_GB beside them (Phase 2,
|
||||
# unsloth_budget), as ISTA's. Else a RAM budget of experts, the rest from the GGUF on the SSD - not the low-RAM
|
||||
# mode (no experts.bin: it would be another 77 GB on the disk), and one GPU (the budget mode had no layer split)
|
||||
# unless the RAM holds the GGUFs and 24 GB more: then several, without the budget, if asked for (#498). #642:
|
||||
# from RESIDENT_SPLIT_ENGINE several GPUs, when asked for, keep the budget (unsloth_together)
|
||||
if MODELS[model].get("experimental"):
|
||||
warn(f"{model} is EXPERIMENTAL (docs/UNSLOTH_Q4.md): most of its experts are read from the SSD while it "
|
||||
"answers, so it is several times slower than the 2-3-bit models; quality checked against llama.cpp")
|
||||
warn(f"{model} is EXPERIMENTAL (docs/UNSLOTH_Q4.md)" + (
|
||||
": most of its experts are read from the SSD while it answers, so it is several times slower than the "
|
||||
"2-3-bit models" if in_budget else "") + "; quality checked against llama.cpp")
|
||||
if hip and MODELS[model].get("nvidia_only"):
|
||||
# #429 (jkuepker): checked before the 111 GB download. The HIP engine has no prompt kernels for its
|
||||
# Q4_K / Q5_K experts (STRATA_MMQ_KQUANTS is CUDA-only) and it has not been run on AMD: asked, not refused
|
||||
@@ -5348,19 +5445,26 @@ def main() -> int:
|
||||
f"or --model {model} --yes to try it on AMD anyway", " Try it anyway?")
|
||||
warn(f"installing {model} on an AMD card, as you chose (please report how it runs)")
|
||||
if ram < MODELS[model]["ram_gb"]:
|
||||
have = resident_budget_gib(model, ram)
|
||||
total = int(MODELS[model]["arena_gb"] / 1.073741824)
|
||||
confirm_risk(f"{model} needs {MODELS[model]['ram_gb']} GB of RAM or more; this PC has {ram:.0f} GB: "
|
||||
f"its RAM budget would be {resident_budget_gib(model, ram)} GiB, so nearly every expert is "
|
||||
"read from the SSD while it answers (very slow), and it may run out of RAM",
|
||||
bool(a.model), a.yes, f"{model} needs {MODELS[model]['ram_gb']} GB of RAM or more; this PC "
|
||||
f"has {ram:.0f} GB", f"choose one of the 2-3-bit models, or --model {model} --yes to "
|
||||
"install it anyway", " Install it anyway?")
|
||||
f"it would keep {have} GiB of its {total} GiB of experts in RAM and read the other "
|
||||
f"{total - have} GiB from the SSD while it answers (single-digit tokens/s on most SSDs), and "
|
||||
"it may run out of RAM", bool(a.model), a.yes,
|
||||
f"{model} needs {MODELS[model]['ram_gb']} GB of RAM or more; this PC has {ram:.0f} GB",
|
||||
f"choose a smaller size, or --model {model} --yes to install it anyway", " Install it anyway?")
|
||||
warn(f"installing {model} with {ram:.0f} GB of RAM, as you chose")
|
||||
budget = budget_choice(model, ram, a.resident_budget_gib)
|
||||
if multi and not unsloth_together(a, model, ram, gpu, chosen):
|
||||
multi, sel, chosen = [], [gpu["index"]], [gpu]
|
||||
q4_split = bool(multi) and not resident_split() # #498: on several GPUs without the RAM budget (#642: kept)
|
||||
if not q4_split:
|
||||
ok(f"RAM budget: {budget:g} GiB of {model}'s experts in RAM, the rest read from the model files on the SSD")
|
||||
if in_budget:
|
||||
budget = budget_choice(model, ram, a.resident_budget_gib)
|
||||
if multi and not unsloth_together(a, model, ram, gpu, chosen):
|
||||
multi, sel, chosen = [], [gpu["index"]], [gpu]
|
||||
q4_split = bool(multi) and not resident_split() # #498: on several GPUs without the RAM budget (#642: kept)
|
||||
if not q4_split:
|
||||
ok(f"RAM budget: {budget:g} GiB of {model}'s experts in RAM, the rest read from the model files on the SSD")
|
||||
else:
|
||||
ok(f"all {MODELS[model]['arena_gb']:.0f} GB of {model}'s experts in RAM (they and "
|
||||
f"{UNSLOTH_RESIDENT_BESIDE_GB} GiB more fit this PC's {ram:.0f} GB; --resident-budget-gib N keeps only "
|
||||
"N GiB of them)")
|
||||
if a.low_ram not in ("auto", "off"):
|
||||
warn(f"--low-ram {a.low_ram} does not apply to {model}: it always reads part of its experts from the files")
|
||||
elif a.resident_budget_gib is not None:
|
||||
@@ -5585,7 +5689,8 @@ def main() -> int:
|
||||
lib_dirs = meta.get("lib_dirs") or meta.get("cuda_dirs") or cuda_lib_dirs(cuda_tk)
|
||||
engine_ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:4] if x.isdigit())
|
||||
need_engine = MODELS[model].get("engine", UNSLOTH_ENGINE)
|
||||
if budget is not None and engine_ver < need_engine: # checked before the 94-111 GB download
|
||||
# checked before the 94-188 GB download
|
||||
if MODELS[model].get("budget") and engine_ver < need_engine:
|
||||
fail(f"{model} needs engine {'.'.join(map(str, need_engine))} or newer; this one is {meta.get('version')}",
|
||||
"update Strata (or compile the engine with --build) and run setup again")
|
||||
ok(f"engine: {eng / EXE}")
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
// src/kernels/cpu/kq_cpu_bench.cpp - MODEL-UPDATE: how close the CPU pool's expert rows come to the RAM bandwidth, per
|
||||
// expert format. No GPU, no model: --mb MB of expert blobs (ggml-quantized random weights, far more than any L3) are
|
||||
// computed by T threads at once through the engine's own entry points (native_gu_rows + native_down_rows, the pool's
|
||||
// calls), each thread walking its own experts, nt tokens per expert - the decode case, where every CPU expert is a
|
||||
// fresh read from DRAM. Prints the weight bytes per second against the --ram-gbs given (a separate read test).
|
||||
//
|
||||
// kq_cpu_bench [--pairs q4_K/q5_1,q5_K/q8_0,q6_K/q8_0,q8_0/q8_0,iq3_s/iq4_nl] [--threads 1,8,16,32] [--nt 1,2,4]
|
||||
// [--mb 4096] [--reps 3] [--ram-gbs N]
|
||||
#include "strata/kernels/cpu/expert_layout.hpp"
|
||||
#include "strata/kernels/cpu/native_expert.hpp"
|
||||
|
||||
#include "ggml.h"
|
||||
#include "ggml-cpu.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace cpu = strata::kernels::cpu;
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int64_t kH = 2560, kFF = 640;
|
||||
constexpr int kMaxT = 8;
|
||||
|
||||
int type_of(const std::string& s) {
|
||||
for (int t = 0; t < GGML_TYPE_COUNT; ++t) {
|
||||
const char* n = ggml_type_name((ggml_type) t);
|
||||
if (n != nullptr && s == n) return t;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
std::vector<std::string> split(const std::string& s) {
|
||||
std::vector<std::string> v;
|
||||
size_t from = 0;
|
||||
for (;;) {
|
||||
const size_t c = s.find(',', from);
|
||||
v.push_back(s.substr(from, c == std::string::npos ? std::string::npos : c - from));
|
||||
if (c == std::string::npos) break;
|
||||
from = c + 1;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
// one expert blob in the GGUF form: gate rows, up rows (n_ff x n_embd each), down rows (n_embd x n_ff), from random
|
||||
// weights quantized by ggml-cpu (valid scales, as a real file has)
|
||||
void make_blob(const cpu::NativeFmt& f, uint8_t* blob, std::mt19937& rng) {
|
||||
std::normal_distribution<float> nd(0.f, 0.02f);
|
||||
std::vector<float> row((size_t) std::max(kH, kFF));
|
||||
const auto* tg = ggml_get_type_traits_cpu((ggml_type) f.gu_type);
|
||||
const auto* td = ggml_get_type_traits_cpu((ggml_type) f.d_type);
|
||||
for (int64_t r = 0; r < 2 * kFF; ++r) {
|
||||
for (int64_t i = 0; i < kH; ++i) row[(size_t) i] = nd(rng);
|
||||
tg->from_float(row.data(), blob + (size_t) r * f.gu_row, kH);
|
||||
}
|
||||
for (int64_t r = 0; r < kH; ++r) {
|
||||
for (int64_t i = 0; i < kFF; ++i) row[(size_t) i] = nd(rng);
|
||||
td->from_float(row.data(), blob + f.down_off + (size_t) r * f.d_row, kFF);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
setvbuf(stdout, nullptr, _IONBF, 0);
|
||||
std::vector<std::string> pairs = split("q4_K/q5_1,q5_K/q8_0,q6_K/q8_0,q8_0/q8_0,iq3_s/iq4_nl");
|
||||
std::vector<int> threads = {1, 8, 16, 32}, nts = {1, 2, 4};
|
||||
int mb = 4096, reps = 3;
|
||||
double ram = 0;
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
const std::string a = argv[i];
|
||||
const bool more = i + 1 < argc;
|
||||
auto ints = [](const std::string& s) { std::vector<int> v; for (auto& x : split(s)) v.push_back(std::atoi(x.c_str())); return v; };
|
||||
if (a == "--pairs" && more) pairs = split(argv[++i]);
|
||||
else if (a == "--threads" && more) threads = ints(argv[++i]);
|
||||
else if (a == "--nt" && more) nts = ints(argv[++i]);
|
||||
else if (a == "--mb" && more) mb = std::atoi(argv[++i]);
|
||||
else if (a == "--reps" && more) reps = std::max(1, std::atoi(argv[++i]));
|
||||
else if (a == "--ram-gbs" && more) ram = std::atof(argv[++i]);
|
||||
else {
|
||||
std::fprintf(stderr, "usage: kq_cpu_bench [--pairs a/b,...] [--threads 1,8] [--nt 1,2,4] [--mb 4096] [--reps 3] [--ram-gbs N]\n");
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
ggml_cpu_init();
|
||||
std::printf("kq_cpu_bench: %s (avx2 %d, avx512 %d), %d MB of blobs per format\n", cpu::cpu_name().c_str(),
|
||||
(int) cpu::cpu_avx2_ok(), (int) cpu::cpu_avx512_ok(), mb);
|
||||
for (const std::string& pair : pairs) {
|
||||
const size_t slash = pair.find('/');
|
||||
const int gt = slash == std::string::npos ? -1 : type_of(pair.substr(0, slash));
|
||||
const int dt = slash == std::string::npos ? -1 : type_of(pair.substr(slash + 1));
|
||||
cpu::NativeFmt f;
|
||||
std::string err;
|
||||
if (gt < 0 || dt < 0 || !cpu::native_fmt(gt, dt, kH, kFF, f, err)) {
|
||||
std::printf("%s: %s\n", pair.c_str(), err.empty() ? "unknown types" : err.c_str());
|
||||
continue;
|
||||
}
|
||||
ggml_quantize_init((ggml_type) gt); // the i-quants' quantizers need their grids first
|
||||
ggml_quantize_init((ggml_type) dt);
|
||||
const size_t E = std::max<size_t>(64, ((size_t) mb << 20) / f.bytes);
|
||||
std::unique_ptr<uint8_t[]> mem(new uint8_t[E * f.bytes + 4096]);
|
||||
uint8_t* blobs = (uint8_t*) (((uintptr_t) mem.get() + 4095) & ~(uintptr_t) 4095);
|
||||
{ // 16 distinct experts, copied over the whole buffer (the bytes in DRAM are what is measured)
|
||||
std::mt19937 rng(1234 + gt * 64 + dt);
|
||||
const size_t U = std::min<size_t>(16, E);
|
||||
for (size_t e = 0; e < U; ++e) make_blob(f, blobs + e * f.bytes, rng);
|
||||
for (size_t e = U; e < E; ++e) std::memcpy(blobs + e * f.bytes, blobs + (e % U) * f.bytes, f.bytes);
|
||||
}
|
||||
// activations: kMaxT tokens of x (n_embd) and h (n_ff), quantized the way the pool quantizes them
|
||||
std::mt19937 rng(77);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
std::vector<std::vector<uint8_t>> xa(kMaxT, std::vector<uint8_t>(cpu::kNativeActBytes)),
|
||||
ha(kMaxT, std::vector<uint8_t>(cpu::kNativeHBytes));
|
||||
const void* act[kMaxT];
|
||||
const void* hq[kMaxT];
|
||||
for (int t = 0; t < kMaxT; ++t) {
|
||||
std::vector<float> x(kH), h(kFF);
|
||||
for (auto& v : x) v = nd(rng);
|
||||
for (auto& v : h) v = 0.1f * nd(rng);
|
||||
cpu::native_quant_act(f, x.data(), xa[t].data());
|
||||
cpu::native_quant_h(f, h.data(), ha[t].data());
|
||||
act[t] = xa[t].data();
|
||||
hq[t] = ha[t].data();
|
||||
}
|
||||
std::printf("\n%s: %zu experts of %.3f MB (%.0f MB)\n", pair.c_str(), E, f.bytes / 1e6, E * (double) f.bytes / 1e6);
|
||||
for (int nt : nts) {
|
||||
for (int T : threads) {
|
||||
if (T < 1) continue;
|
||||
std::vector<double> gbs;
|
||||
for (int rep = 0; rep < reps; ++rep) {
|
||||
std::atomic<size_t> next{0};
|
||||
auto work = [&] {
|
||||
std::vector<float> ffb((size_t) kMaxT * kFF), outb((size_t) kMaxT * kH);
|
||||
float* ff[kMaxT];
|
||||
float* out[kMaxT];
|
||||
for (int t = 0; t < kMaxT; ++t) { ff[t] = &ffb[(size_t) t * kFF]; out[t] = &outb[(size_t) t * kH]; }
|
||||
std::vector<std::vector<uint8_t>> hb(kMaxT, std::vector<uint8_t>(cpu::kNativeHBytes));
|
||||
for (;;) {
|
||||
const size_t e = next.fetch_add(1);
|
||||
if (e >= E) break;
|
||||
const uint8_t* blob = blobs + e * f.bytes;
|
||||
cpu::native_gu_rows(f, blob, act, nt, ff, 0, (int) kFF);
|
||||
cpu::native_down_rows(f, blob, hq, nt, out, 0, (int) kH);
|
||||
}
|
||||
volatile float sink = outb[0] + ffb[0];
|
||||
(void) sink;
|
||||
};
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
std::vector<std::thread> th;
|
||||
for (int k = 0; k < T; ++k) th.emplace_back(work);
|
||||
for (auto& x : th) x.join();
|
||||
const double s = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
|
||||
gbs.push_back(E * (double) f.bytes / s / 1e9);
|
||||
}
|
||||
std::sort(gbs.begin(), gbs.end());
|
||||
const double med = gbs[gbs.size() / 2];
|
||||
std::printf(" nt %d threads %2d: %6.1f GB/s of weights (%.3f ms per expert per thread)%s\n", nt, T, med,
|
||||
f.bytes / (med * 1e9 / T) * 1e3,
|
||||
ram > 0 ? (" = " + std::to_string((int) std::lround(100 * med / ram)) + "% of RAM").c_str() : "");
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -27,6 +27,7 @@
|
||||
#include "strata/kernels/dp4a.hpp"
|
||||
#include "strata/kernels/q8_1_finite.hpp"
|
||||
#include "strata/kernels/iq_kernels.hpp"
|
||||
#include "strata/kernels/gfx_arch.hpp"
|
||||
#include "s26_tsum.cuh"
|
||||
#if !defined(__HIPCC__)
|
||||
#include "q8_1_il.cuh"
|
||||
@@ -42,6 +43,7 @@
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
#include <type_traits>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <cstdio>
|
||||
@@ -1258,6 +1260,49 @@ __global__ void native_mmvq_multi_kernel(const typename F::Block* __restrict__ w
|
||||
}
|
||||
}
|
||||
|
||||
// MODEL-UPDATE: the dense Q8_0 projections of Unsloth's files (all of attention, SSM and the shared expert are Q8_0
|
||||
// there) take one row per block where that was measured faster - the same per-row sums and reduction as two rows per
|
||||
// block (each row its own partials), so every output is the same bits. q8_gemv_bench, 2-4 columns:
|
||||
// gfx1201 (R9700): n_in <= 4096 with n_out >= 4096 (qkv 2560->10240 73-79% -> 83-84% of the 644 GB/s, gate 2560->6144
|
||||
// 51-68% -> 76-78%, q 2560->12288 74-80% -> 85-86%); 6144->2560 is slower there (79% -> 55-59%) and keeps two rows.
|
||||
// sm_86 (RTX A4000): every n_out >= 2048 (+1-4% at 2-4 columns, 6144->2560 at 6 columns 70% -> 76%).
|
||||
// Other cards keep two rows until measured (STRATA_NO_MMVQ_ROWS2=1 forces one row everywhere; =0 keeps two everywhere).
|
||||
int dev_class() { // 1 = gfx12, 2 = sm_86, 0 = the rest; per device
|
||||
static int cls[16]; // 0 unknown, else class + 1
|
||||
int dev = 0;
|
||||
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 16) return 0;
|
||||
if (cls[dev] == 0) {
|
||||
int c = 0;
|
||||
#if defined(__HIPCC__)
|
||||
cudaDeviceProp p;
|
||||
if (cudaGetDeviceProperties(&p, dev) == cudaSuccess && strata::kernels::gfx_arch_is_gfx12(p.gcnArchName)) c = 1;
|
||||
#else
|
||||
int major = 0, minor = 0;
|
||||
if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
|
||||
cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) == cudaSuccess && major == 8 && minor == 6)
|
||||
c = 2;
|
||||
#endif
|
||||
(void) cudaGetLastError();
|
||||
cls[dev] = c + 1;
|
||||
}
|
||||
return cls[dev] - 1;
|
||||
}
|
||||
template<typename F>
|
||||
bool q8_0_rows1(int n_in, int n_out) {
|
||||
if constexpr (!std::is_same_v<F, SmallTraits<Q80Block, 8>>) {
|
||||
(void) n_in; (void) n_out;
|
||||
return false;
|
||||
} else {
|
||||
static const int env = [] {
|
||||
const char* v = std::getenv("STRATA_NO_MMVQ_ROWS2");
|
||||
return v == nullptr || v[0] == '\0' ? -1 : v[0] != '0';
|
||||
}();
|
||||
if (env == 0) return false;
|
||||
const int c = dev_class();
|
||||
return (c == 1 && n_in <= 4096 && n_out >= 4096) || (c == 2 && n_out >= 2048);
|
||||
}
|
||||
}
|
||||
|
||||
template<typename F, int NCOLS>
|
||||
void launch_multi_n(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, cudaStream_t s) {
|
||||
const auto* w = static_cast<const typename F::Block*>(weights);
|
||||
@@ -1279,7 +1324,7 @@ void launch_multi_n(const void* weights, const void* x_q8_1, float* y, int n_in,
|
||||
const char* v = std::getenv("STRATA_NO_MMVQ_ROWS2");
|
||||
return v != nullptr && v[0] != '\0' && v[0] != '0';
|
||||
}();
|
||||
if (rows1 && n_in / F::DIV >= F::BPI) {
|
||||
if ((rows1 || q8_0_rows1<F>(n_in, n_out)) && n_in / F::DIV >= F::BPI) {
|
||||
if (s26_tsum_on()) launch_pdl(native_mmvq_multi_kernel<F, NCOLS, WARPS, 1, true, false>, dim3(unsigned(n_out)), threads, 0, s, w, x, y, n_in, n_out, no_w2, no_y2);
|
||||
else launch_pdl(native_mmvq_multi_kernel<F, NCOLS, WARPS, 1, false, false>, dim3(unsigned(n_out)), threads, 0, s, w, x, y, n_in, n_out, no_w2, no_y2);
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
// src/kernels/q8_gemv_bench.cpp - MODEL-UPDATE: the dense Q8_0 GEMVs of Unsloth's files (attention, SSM, shared expert,
|
||||
// hyper-connections, head: all Q8_0 there) at the engine's shapes, 1..6 columns (a verify window's tokens), through
|
||||
// native_mmvq - the call the engine makes - against the card's memory bandwidth. Enough copies of each matrix are
|
||||
// cycled to miss the GPU's last-level cache, as a layer's call does.
|
||||
//
|
||||
// build/q8_gemv_bench [--cols 1,2,3,4,6] [--iters 50] [--bw GB/s]
|
||||
#include "strata/kernels/native_mmvq.hpp"
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace K = strata::kernels;
|
||||
|
||||
namespace {
|
||||
struct Shape { const char* what; int n_in, n_out; };
|
||||
const Shape SHAPES[] = {
|
||||
{"GDN qkv 2560->10240", 2560, 10240}, {"GDN gate 2560->6144", 2560, 6144}, {"GDN/QSA out 6144->2560", 6144, 2560},
|
||||
{"QSA q 2560->12288", 2560, 12288}, {"QSA k/v 2560->512", 2560, 512}, {"HC down 10240->320", 10240, 320},
|
||||
{"HC up 320->10240", 320, 10240}, {"shared gate/up 2560->640", 2560, 640}, {"shared down 640->2560", 640, 2560},
|
||||
{"head 2560->248320", 2560, 248320},
|
||||
};
|
||||
void ck(cudaError_t e, const char* w) {
|
||||
if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(1); }
|
||||
}
|
||||
std::vector<int> ints(const std::string& s) {
|
||||
std::vector<int> v;
|
||||
size_t from = 0;
|
||||
for (;;) {
|
||||
const size_t c = s.find(',', from);
|
||||
v.push_back(std::atoi(s.substr(from, c == std::string::npos ? std::string::npos : c - from).c_str()));
|
||||
if (c == std::string::npos) break;
|
||||
from = c + 1;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
std::vector<int> cols = {1, 2, 3, 4, 6};
|
||||
int iters = 50;
|
||||
double bw = 0;
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
const std::string a = argv[i];
|
||||
if (a == "--cols" && i + 1 < argc) cols = ints(argv[++i]);
|
||||
else if (a == "--iters" && i + 1 < argc) iters = std::atoi(argv[++i]);
|
||||
else if (a == "--bw" && i + 1 < argc) bw = std::atof(argv[++i]);
|
||||
}
|
||||
cudaDeviceProp prop;
|
||||
ck(cudaGetDeviceProperties(&prop, 0), "props");
|
||||
std::printf("q8_gemv_bench: %s\n", prop.name);
|
||||
std::mt19937 rng(7);
|
||||
for (const Shape& s : SHAPES) {
|
||||
const size_t bytes = (size_t) s.n_out * (s.n_in / 32) * 34;
|
||||
const int copies = (int) std::max<size_t>(1, std::min<size_t>(16, ((size_t) 512 << 20) / bytes));
|
||||
std::vector<uint8_t> host(bytes);
|
||||
for (size_t b = 0; b < bytes; b += 34) { // fp16 scale 0.01 (0x211f), then random int8 weights
|
||||
host[b] = 0x1f;
|
||||
host[b + 1] = 0x21;
|
||||
for (int k = 0; k < 32; ++k) host[b + 2 + k] = (uint8_t) (rng() & 0xff);
|
||||
}
|
||||
std::vector<void*> w(copies);
|
||||
for (auto& p : w) {
|
||||
ck(cudaMalloc(&p, bytes), "malloc w");
|
||||
ck(cudaMemcpy(p, host.data(), bytes, cudaMemcpyHostToDevice), "copy w");
|
||||
}
|
||||
const int maxc = *std::max_element(cols.begin(), cols.end());
|
||||
std::vector<float> xh((size_t) s.n_in * maxc);
|
||||
for (auto& v : xh) v = std::normal_distribution<float>(0.f, 1.f)(rng);
|
||||
float *x = nullptr, *y = nullptr;
|
||||
void* xq = nullptr;
|
||||
ck(cudaMalloc(&x, xh.size() * 4), "x");
|
||||
ck(cudaMemcpy(x, xh.data(), xh.size() * 4, cudaMemcpyHostToDevice), "x copy");
|
||||
ck(cudaMalloc(&xq, K::native_q8_1_bytes(s.n_in, maxc)), "xq");
|
||||
ck(cudaMalloc(&y, (size_t) s.n_out * maxc * 4), "y");
|
||||
cudaStream_t st;
|
||||
ck(cudaStreamCreate(&st), "stream");
|
||||
cudaEvent_t e0, e1;
|
||||
cudaEventCreate(&e0);
|
||||
cudaEventCreate(&e1);
|
||||
std::printf("\n%s: %.2f MB, %d copies\n", s.what, bytes / 1e6, copies);
|
||||
for (int c : cols) {
|
||||
K::native_quantize_q8_1(x, xq, s.n_in, c, st);
|
||||
for (int i = 0; i < 3; ++i) K::native_mmvq(8, w[i % copies], xq, y, s.n_in, s.n_out, c, st);
|
||||
cudaEventRecord(e0, st);
|
||||
for (int i = 0; i < iters; ++i) K::native_mmvq(8, w[i % copies], xq, y, s.n_in, s.n_out, c, st);
|
||||
cudaEventRecord(e1, st);
|
||||
ck(cudaEventSynchronize(e1), "sync");
|
||||
float ms = 0;
|
||||
cudaEventElapsedTime(&ms, e0, e1);
|
||||
const double us = 1000.0 * ms / iters, gbs = bytes / (us * 1e3);
|
||||
std::printf(" %d col%s: %8.1f us %7.1f GB/s%s\n", c, c == 1 ? " " : "s", us, gbs,
|
||||
bw > 0 ? (" = " + std::to_string((int) (100 * gbs / bw + 0.5)) + "% of bw").c_str() : "");
|
||||
}
|
||||
for (auto p : w) cudaFree(p);
|
||||
cudaFree(x);
|
||||
cudaFree(xq);
|
||||
cudaFree(y);
|
||||
cudaStreamDestroy(st);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// src/prefill/mmq_kq_lib.cu - strata_kq, the shared library with llama.cpp's MMQ prompt kernels for the K-quants
|
||||
// (Q4_K, Q5_K, Q5_1, Q6_K: the experts of Unsloth's UD-Q4/Q5/Q6_K_XL files). MODEL-UPDATE Phase 1: the engine loads
|
||||
// every kernel of its own binary when it starts (CUDA_MODULE_LOADING=EAGER, src/program/generate.cpp), so kernels in
|
||||
// the engine cost every model VRAM; these four instances were ~3.8 MB of sm_60 code (3 expert slots of IQ3_XXS on a
|
||||
// P100). Here they load only when moe_mmq.cu opens this library - for a model with these experts, before the expert
|
||||
// cache is sized - and never otherwise. The library has its own copy of ggml_cuda_host.cu's symbols and of the static
|
||||
// CUDA runtime; it works in the engine's context on the stream it is given.
|
||||
#include "common.cuh"
|
||||
#include "mmq.cuh"
|
||||
|
||||
#include "strata/prefill/mmq_kq_abi.hpp"
|
||||
|
||||
#include <mutex>
|
||||
|
||||
#if defined(_WIN32)
|
||||
#define STRATA_KQ_EXPORT extern "C" __declspec(dllexport)
|
||||
#else
|
||||
#define STRATA_KQ_EXPORT extern "C" __attribute__((visibility("default")))
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
std::mutex g_mu;
|
||||
ggml_backend_cuda_context* g_ctx[GGML_CUDA_MAX_DEVICES] = {};
|
||||
|
||||
ggml_backend_cuda_context* ctx_for(int dev) {
|
||||
std::lock_guard<std::mutex> lk(g_mu);
|
||||
if (g_ctx[dev] == nullptr) g_ctx[dev] = new ggml_backend_cuda_context(dev);
|
||||
return g_ctx[dev];
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// the interface version and the argument block's size: both sides are compiled from the same mmq.cuh
|
||||
STRATA_KQ_EXPORT int strata_kq_abi() { return STRATA_KQ_ABI_VERSION * 100000 + (int) sizeof(mmq_args); }
|
||||
|
||||
// Starts this library's CUDA runtime in the engine's context on `device`: with CUDA_MODULE_LOADING=EAGER (the engine
|
||||
// sets it before its first CUDA call) that loads every kernel here now, while the VRAM for it is still free.
|
||||
// 0 = ready, else the cudaError_t.
|
||||
STRATA_KQ_EXPORT int strata_kq_init(int device) {
|
||||
cudaError_t e = cudaSetDevice(device);
|
||||
if (e == cudaSuccess) e = cudaFree(nullptr);
|
||||
return (int) e;
|
||||
}
|
||||
|
||||
// One MMQ product (moe_mmq.cu's Context::run for these types) on `device`, on the engine's `stream`. 0 = launched, -1 =
|
||||
// a type this library does not have, else the cudaError_t of the launch.
|
||||
STRATA_KQ_EXPORT int strata_kq_run(int device, int type, const void* args, void* stream) {
|
||||
if (device < 0 || device >= GGML_CUDA_MAX_DEVICES) return -1;
|
||||
if (cudaSetDevice(device) != cudaSuccess) return (int) cudaGetLastError();
|
||||
ggml_backend_cuda_context& ctx = *ctx_for(device);
|
||||
const mmq_args& a = *(const mmq_args*) args;
|
||||
const cudaStream_t s = (cudaStream_t) stream;
|
||||
switch ((ggml_type) type) {
|
||||
case GGML_TYPE_Q4_K: mul_mat_q_case<GGML_TYPE_Q4_K>(ctx, a, s); break;
|
||||
case GGML_TYPE_Q5_K: mul_mat_q_case<GGML_TYPE_Q5_K>(ctx, a, s); break;
|
||||
case GGML_TYPE_Q5_1: mul_mat_q_case<GGML_TYPE_Q5_1>(ctx, a, s); break;
|
||||
case GGML_TYPE_Q6_K: mul_mat_q_case<GGML_TYPE_Q6_K>(ctx, a, s); break;
|
||||
default: return -1;
|
||||
}
|
||||
return (int) cudaGetLastError();
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// src/prefill/mmq_kq_loader.cpp - opens strata_kq (src/prefill/mmq_kq_lib.cu), the library with the K-quant MMQ prompt
|
||||
// kernels, from the engine's own folder - once, for the first model format that asks for it (moe_mmq.cu's supported()),
|
||||
// which the engine does before it sizes the expert cache (src/program/generate.cpp). Without the library, or with an
|
||||
// interface of another version, the K-quants keep the FP16 prompt path and the engine says so once.
|
||||
#include "strata/prefill/mmq_kq_abi.hpp"
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
||||
#if defined(_WIN32)
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
#else
|
||||
#include <dlfcn.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace strata::prefill::mmq::kq {
|
||||
namespace {
|
||||
|
||||
struct Lib {
|
||||
bool ok = false;
|
||||
strata_kq_run_fn run = nullptr;
|
||||
};
|
||||
|
||||
std::string own_folder() {
|
||||
#if defined(_WIN32)
|
||||
char p[MAX_PATH] = {};
|
||||
const DWORD n = GetModuleFileNameA(nullptr, p, MAX_PATH);
|
||||
std::string s(p, n);
|
||||
const size_t k = s.find_last_of("\\/");
|
||||
return k == std::string::npos ? std::string() : s.substr(0, k + 1);
|
||||
#else
|
||||
char p[4096] = {};
|
||||
const ssize_t n = readlink("/proc/self/exe", p, sizeof(p) - 1);
|
||||
std::string s(p, n > 0 ? (size_t) n : 0);
|
||||
const size_t k = s.find_last_of('/');
|
||||
return k == std::string::npos ? std::string() : s.substr(0, k + 1);
|
||||
#endif
|
||||
}
|
||||
|
||||
void* sym(void* h, const char* name) {
|
||||
#if defined(_WIN32)
|
||||
return reinterpret_cast<void*>(GetProcAddress((HMODULE) h, name));
|
||||
#else
|
||||
return dlsym(h, name);
|
||||
#endif
|
||||
}
|
||||
|
||||
Lib open_lib() {
|
||||
Lib L;
|
||||
const std::string path = own_folder() + STRATA_KQ_LIB_NAME;
|
||||
#if defined(_WIN32)
|
||||
void* h = (void*) LoadLibraryA(path.c_str());
|
||||
#else
|
||||
void* h = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL);
|
||||
#endif
|
||||
if (h == nullptr) {
|
||||
std::fprintf(stderr, "strata: K-quant prompt kernels (STRATA_MMQ_KQ=1): %s not found next to the engine - "
|
||||
"these experts take the FP16 prompt path\n", STRATA_KQ_LIB_NAME);
|
||||
return L;
|
||||
}
|
||||
const auto abi = (strata_kq_abi_fn) sym(h, "strata_kq_abi");
|
||||
const auto init = (strata_kq_init_fn) sym(h, "strata_kq_init");
|
||||
L.run = (strata_kq_run_fn) sym(h, "strata_kq_run");
|
||||
if (abi == nullptr || init == nullptr || L.run == nullptr || abi() / 100000 != STRATA_KQ_ABI_VERSION ||
|
||||
abi() % 100000 != abi_args_size()) {
|
||||
std::fprintf(stderr, "strata: K-quant prompt kernels: %s is from another engine version - these experts take "
|
||||
"the FP16 prompt path\n", path.c_str());
|
||||
L.run = nullptr;
|
||||
return L;
|
||||
}
|
||||
// every GPU this engine sees: each context loads the library's kernels now, while the VRAM is still free
|
||||
int n = 0, cur = 0;
|
||||
cudaGetDevice(&cur);
|
||||
if (cudaGetDeviceCount(&n) != cudaSuccess) n = 0;
|
||||
for (int d = 0; d < n; ++d) {
|
||||
const int e = init(d);
|
||||
if (e != 0) {
|
||||
std::fprintf(stderr, "strata: K-quant prompt kernels: %s did not start on GPU %d (CUDA error %d) - these "
|
||||
"experts take the FP16 prompt path\n", path.c_str(), d, e);
|
||||
L.run = nullptr;
|
||||
cudaSetDevice(cur);
|
||||
return L;
|
||||
}
|
||||
}
|
||||
cudaSetDevice(cur);
|
||||
std::fprintf(stderr, "strata: K-quant prompt kernels from %s (STRATA_MMQ_KQ=1)\n", path.c_str());
|
||||
L.ok = true;
|
||||
return L;
|
||||
}
|
||||
|
||||
const Lib& lib() {
|
||||
static const Lib L = open_lib();
|
||||
return L;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool wanted() {
|
||||
static const bool on = [] {
|
||||
const char* v = std::getenv("STRATA_MMQ_KQ");
|
||||
return v != nullptr && v[0] == '1';
|
||||
}();
|
||||
return on;
|
||||
}
|
||||
|
||||
bool available() { return wanted() && lib().ok; }
|
||||
|
||||
int run(int type, const void* args, void* stream) {
|
||||
int dev = 0;
|
||||
cudaGetDevice(&dev);
|
||||
return lib().ok ? lib().run(dev, type, args, stream) : -1;
|
||||
}
|
||||
|
||||
} // namespace strata::prefill::mmq::kq
|
||||
+37
-9
@@ -7,11 +7,33 @@
|
||||
#include "mmq.cuh"
|
||||
#include "quantize.cuh"
|
||||
|
||||
#include "strata/prefill/mmq_kq_abi.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
|
||||
namespace strata::prefill::mmq {
|
||||
#if defined(STRATA_KQ_DSO)
|
||||
namespace kq {
|
||||
int abi_args_size() { return (int) sizeof(mmq_args); }
|
||||
} // namespace kq
|
||||
#endif
|
||||
namespace {
|
||||
#if defined(STRATA_MMQ_KQUANTS)
|
||||
// MODEL-UPDATE Phase 1: the K-quant products through MMQ are opt-in at run time (STRATA_MMQ_KQ=1); on CUDA their
|
||||
// kernels are the strata_kq library (mmq_kq_loader.cpp), opened only then
|
||||
bool kq_ok() {
|
||||
#if defined(STRATA_KQ_DSO)
|
||||
return kq::available();
|
||||
#else
|
||||
static const bool on = [] {
|
||||
const char* v = std::getenv("STRATA_MMQ_KQ");
|
||||
return v != nullptr && v[0] == '1';
|
||||
}();
|
||||
return on;
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
void ck(cudaError_t e, const char* what) {
|
||||
if (e != cudaSuccess) {
|
||||
@@ -127,13 +149,12 @@ bool supported(int t) {
|
||||
case GGML_TYPE_IQ2_XXS: case GGML_TYPE_IQ2_XS: case GGML_TYPE_IQ2_S:
|
||||
case GGML_TYPE_IQ3_XXS: case GGML_TYPE_IQ3_S: case GGML_TYPE_IQ4_NL: case GGML_TYPE_IQ4_XS:
|
||||
case GGML_TYPE_Q8_0: // the draft layer's dense matrices (E-9)
|
||||
#ifdef STRATA_MMQ_KQUANTS
|
||||
case GGML_TYPE_Q4_K: case GGML_TYPE_Q5_K: case GGML_TYPE_Q5_1: // Unsloth's UD-Q4_K_XL experts (CUDA)
|
||||
#if defined(__HIPCC__) || defined(STRATA_Q6K_EXPERTS)
|
||||
case GGML_TYPE_Q6_K: // HIP: the dense GGUF projections (STRATA_DENSE_MMQ); CUDA: only the opt-in -DSTRATA_Q6K_EXPERTS=ON build
|
||||
#endif
|
||||
#endif
|
||||
return true;
|
||||
#ifdef STRATA_MMQ_KQUANTS
|
||||
// Unsloth's UD-Q4/Q5/Q6_K_XL experts; on HIP also the dense GGUF projections (STRATA_DENSE_MMQ)
|
||||
case GGML_TYPE_Q4_K: case GGML_TYPE_Q5_K: case GGML_TYPE_Q5_1: case GGML_TYPE_Q6_K:
|
||||
return kq_ok();
|
||||
#endif
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
@@ -213,12 +234,19 @@ void Context::run(const Product& p, void* stream) {
|
||||
case GGML_TYPE_IQ4_NL: mul_mat_q_case<GGML_TYPE_IQ4_NL>(ctx, a, s); break;
|
||||
case GGML_TYPE_IQ4_XS: mul_mat_q_case<GGML_TYPE_IQ4_XS>(ctx, a, s); break;
|
||||
case GGML_TYPE_Q8_0: mul_mat_q_case<GGML_TYPE_Q8_0>(ctx, a, s); break;
|
||||
#ifdef STRATA_MMQ_KQUANTS
|
||||
#if defined(STRATA_MMQ_KQUANTS) && defined(STRATA_KQ_DSO)
|
||||
case GGML_TYPE_Q4_K: case GGML_TYPE_Q5_K: case GGML_TYPE_Q6_K: case GGML_TYPE_Q5_1: {
|
||||
const int e = kq::run((int) t, &a, s);
|
||||
if (e != 0) {
|
||||
std::fprintf(stderr, "prefill mmq: the K-quant library failed on type %d (error %d)\n", (int) t, e);
|
||||
std::exit(1);
|
||||
}
|
||||
break;
|
||||
}
|
||||
#elif defined(STRATA_MMQ_KQUANTS)
|
||||
case GGML_TYPE_Q4_K: mul_mat_q_case<GGML_TYPE_Q4_K>(ctx, a, s); break;
|
||||
case GGML_TYPE_Q5_K: mul_mat_q_case<GGML_TYPE_Q5_K>(ctx, a, s); break;
|
||||
#if defined(__HIPCC__) || defined(STRATA_Q6K_EXPERTS)
|
||||
case GGML_TYPE_Q6_K: mul_mat_q_case<GGML_TYPE_Q6_K>(ctx, a, s); break;
|
||||
#endif
|
||||
case GGML_TYPE_Q5_1: mul_mat_q_case<GGML_TYPE_Q5_1>(ctx, a, s); break;
|
||||
#endif
|
||||
default:
|
||||
|
||||
@@ -62,6 +62,9 @@
|
||||
#include "strata/core/verify.hpp"
|
||||
#include "strata/core/mtp.hpp"
|
||||
#include "strata/prefill/prefill.hpp"
|
||||
#if defined(STRATA_PREFILL_MMQ)
|
||||
#include "strata/prefill/moe_mmq.hpp"
|
||||
#endif
|
||||
#include "strata/core/native_dense.hpp"
|
||||
#include "strata/program/batch_read.hpp"
|
||||
#include "strata/program/logits_selection.hpp"
|
||||
@@ -2770,6 +2773,12 @@ int main(int argc, char** argv) {
|
||||
f.gu_type, f.d_type);
|
||||
return 1;
|
||||
}
|
||||
#if defined(STRATA_PREFILL_MMQ)
|
||||
// MODEL-UPDATE Phase 1: the K-quants' prompt kernels (STRATA_MMQ_KQ=1) are a library of their own on CUDA
|
||||
// (strata_kq): asking for the formats opens it now, before the expert cache takes the free VRAM
|
||||
(void) strata::prefill::mmq::supported(f.gu_type);
|
||||
(void) strata::prefill::mmq::supported(f.d_type);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
const bool native_pack = strata::kernels::cpu::expert_layout().native;
|
||||
|
||||
@@ -149,6 +149,12 @@ find_package(Threads REQUIRED)
|
||||
target_link_libraries(strata_kernels_cpu PUBLIC strata_includes Threads::Threads)
|
||||
|
||||
option(STRATA_NATIVE_EXPERTS "Native (IQ) expert support through ggml-cpu" ON)
|
||||
# Q6_K gate/up in the grouped expert kernels (UD-Q6_K_XL, layer 2 of UD-Q5_K_XL): on by default, as in the CUDA / HIP
|
||||
# build (MODEL-UPDATE Phase 1)
|
||||
option(STRATA_Q6K_EXPERTS "Build the Q6_K gate/up grouped expert kernels (UD-Q6_K_XL, UD-Q5_K_XL)" ON)
|
||||
if(STRATA_Q6K_EXPERTS)
|
||||
add_compile_definitions(STRATA_Q6K_EXPERTS=1)
|
||||
endif()
|
||||
set(STRATA_GGML_DIR "" CACHE PATH "llama.cpp checkout to take ggml from (empty: fetch the pinned commit)")
|
||||
if(STRATA_NATIVE_EXPERTS)
|
||||
set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE)
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Decode bounds of a quant from its real per-layer formats (tools/quant_formats.py --json output).
|
||||
|
||||
python tools/quant_bound.py FMT.json [...] --ram-gbs 120 [--vram-gbs 640] [--hit 0.3] [--tokens-per-pass 1]
|
||||
|
||||
Per token: the routed experts (10 of 512 per layer: each layer's gate + up + down bytes / 512 x 10), the shared expert
|
||||
and the dense side (attention, SSM, hyper-connections, router, head: read once per pass on the GPU). The bound for a
|
||||
pass of P tokens (a verify window) with a VRAM hit fraction h of the routed experts:
|
||||
t_cpu = (1 - h) x routed bytes x U(P) / RAM bandwidth (the CPU pool reads every missed expert once per pass)
|
||||
t_gpu = (h x routed x U(P) + dense) / VRAM bandwidth
|
||||
tok/s <= P / max(t_cpu, t_gpu)
|
||||
U(P) is the distinct experts a pass of P tokens reads per expert a single token reads (1 for P = 1; measured from
|
||||
the engine's window logs where known, else --union). The CPU line alone (h = 0) is the floor of the all-on-CPU case.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import pathlib
|
||||
|
||||
TOPK, N_EXPERT = 10, 512
|
||||
|
||||
|
||||
def bytes_of(js: dict) -> dict:
|
||||
roles = js["roles"]
|
||||
tot = lambda role: sum(v["bytes"] for v in roles.get(role, {}).values())
|
||||
routed_all = tot("routed gate") + tot("routed up") + tot("routed down")
|
||||
per_token = routed_all / N_EXPERT * TOPK
|
||||
dense = sum(tot(r) for r in ("shared expert", "router", "attention", "SSM", "hyper-connections", "indexer",
|
||||
"PLE key/value", "output head"))
|
||||
return {"routed_all": routed_all, "routed_per_token": per_token, "dense_per_pass": dense,
|
||||
"expert_bytes": routed_all / 48 / N_EXPERT}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("fmt", nargs="+")
|
||||
ap.add_argument("--ram-gbs", type=float, required=True, help="measured RAM read bandwidth, GB/s")
|
||||
ap.add_argument("--vram-gbs", type=float, default=0, help="GPU memory bandwidth, GB/s (0: no GPU line)")
|
||||
ap.add_argument("--hit", type=float, default=0.0, help="VRAM hit fraction of the routed experts")
|
||||
ap.add_argument("--tokens-per-pass", type=float, default=1.0)
|
||||
ap.add_argument("--union", type=float, default=1.0, help="distinct experts per pass / experts per token")
|
||||
a = ap.parse_args()
|
||||
print(f"{'quant':12s} {'expert MB':>9s} {'routed MB/tok':>13s} {'dense MB':>9s} {'CPU-only tok/s':>15s} "
|
||||
f"{'bound tok/s':>11s}")
|
||||
for f in a.fmt:
|
||||
b = bytes_of(json.loads(pathlib.Path(f).read_text()))
|
||||
r = b["routed_per_token"] * a.union
|
||||
t_cpu = (1 - a.hit) * r / (a.ram_gbs * 1e9)
|
||||
t_gpu = (a.hit * r + b["dense_per_pass"]) / (a.vram_gbs * 1e9) if a.vram_gbs else 0.0
|
||||
cpu_only = 1 / (b["routed_per_token"] / (a.ram_gbs * 1e9))
|
||||
bound = a.tokens_per_pass / max(t_cpu, t_gpu) if max(t_cpu, t_gpu) > 0 else float("inf")
|
||||
print(f"{pathlib.Path(f).stem:12s} {b['expert_bytes'] / 1e6:9.2f} {b['routed_per_token'] / 1e6:13.1f} "
|
||||
f"{b['dense_per_pass'] / 1e6:9.1f} {cpu_only:15.1f} {bound:11.1f}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,154 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Per-layer tensor formats of a (sharded) GGUF, read from the headers only (docs/QUANTS.md).
|
||||
|
||||
python tools/quant_formats.py PATH-OR-GLOB [...] local shards (any shard; all are read)
|
||||
python tools/quant_formats.py --hf REPO REV DIR [--json OUT] Hugging Face: HTTP range requests on each shard's
|
||||
header, nothing else is downloaded
|
||||
|
||||
Prints, per role (routed gate / up / down, shared expert, attention, SSM, hyper-connections, indexer, PLE, embedding,
|
||||
head): the formats and the layers each one covers, and the bytes; then the routed experts layer by layer.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import glob
|
||||
import io
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
import gguf_reader as G # noqa: E402
|
||||
|
||||
ROLES = [
|
||||
("routed gate", r"ffn_gate_exps"), ("routed up", r"ffn_up_exps"), ("routed down", r"ffn_down_exps"),
|
||||
("shared expert", r"ffn_(gate|up|down)_shexp\.weight"), ("router", r"ffn_gate_inp"),
|
||||
("attention", r"attn_(q|k|v|qkv|gate|output)\.weight"), ("SSM", r"ssm_(alpha|beta|out)\.weight"),
|
||||
("hyper-connections", r"hc_(attn|ffn)_(up|down|inject)\.weight"), ("indexer", r"indexer\.(q|k)_proj"),
|
||||
("PLE key/value", r"ple_(key|value)\.weight"), ("PLE table", r"^per_layer_token_embd"),
|
||||
("token embedding", r"^token_embd"), ("output head", r"^output(_hc_(up|down))?\.weight"),
|
||||
]
|
||||
|
||||
|
||||
class RangeFile(io.RawIOBase):
|
||||
"""A read-only, forward-reading file over HTTP range requests (4 MiB at a time)."""
|
||||
|
||||
CHUNK = 4 << 20
|
||||
|
||||
def __init__(self, url: str):
|
||||
self.url, self.pos, self.buf, self.buf_at = url, 0, b"", 0
|
||||
|
||||
def _fill(self, need_to: int) -> None:
|
||||
while self.buf_at + len(self.buf) < need_to:
|
||||
start = self.buf_at + len(self.buf)
|
||||
req = urllib.request.Request(self.url, headers={"Range": f"bytes={start}-{start + self.CHUNK - 1}"})
|
||||
data = urllib.request.urlopen(req, timeout=120).read()
|
||||
if not data:
|
||||
raise EOFError(self.url)
|
||||
self.buf += data
|
||||
|
||||
def read(self, n: int = -1) -> bytes:
|
||||
self._fill(self.pos + n)
|
||||
off = self.pos - self.buf_at
|
||||
out = self.buf[off:off + n]
|
||||
self.pos += len(out)
|
||||
return out
|
||||
|
||||
def tell(self) -> int:
|
||||
return self.pos
|
||||
|
||||
|
||||
class Header(G.GGUFFile):
|
||||
def __init__(self, name: str, fh): # noqa: D107 (reuses GGUFFile's parser on any file-like)
|
||||
self.path = pathlib.Path(name)
|
||||
self.metadata, self.tensors, self.version, self.alignment = {}, [], 0, 32
|
||||
self._parse(fh)
|
||||
|
||||
|
||||
def hf_headers(repo: str, rev: str, d: str) -> list[Header]:
|
||||
tree = json.load(urllib.request.urlopen(f"https://huggingface.co/api/models/{repo}/tree/{rev}/{d}", timeout=60))
|
||||
out = []
|
||||
for e in sorted(tree, key=lambda e: e["path"]):
|
||||
if e["type"] == "file" and e["path"].endswith(".gguf"):
|
||||
url = f"https://huggingface.co/{repo}/resolve/{rev}/{e['path']}"
|
||||
out.append(Header(e["path"], RangeFile(url)))
|
||||
return out
|
||||
|
||||
|
||||
def ranges(layers: list[int]) -> str:
|
||||
layers = sorted(layers)
|
||||
out, i = [], 0
|
||||
while i < len(layers):
|
||||
j = i
|
||||
while j + 1 < len(layers) and layers[j + 1] == layers[j] + 1:
|
||||
j += 1
|
||||
out.append(str(layers[i]) if i == j else f"{layers[i]}-{layers[j]}")
|
||||
i = j + 1
|
||||
return ", ".join(out)
|
||||
|
||||
|
||||
def summarize(heads: list[Header]) -> dict:
|
||||
roles: dict[str, dict[str, dict]] = {}
|
||||
per_layer: dict[int, dict[str, str]] = {}
|
||||
for h in heads:
|
||||
for t in h.tensors:
|
||||
m = re.match(r"blk\.(\d+)\.", t.name)
|
||||
layer = int(m.group(1)) if m else -1
|
||||
for role, pat in ROLES:
|
||||
if re.search(pat, t.name):
|
||||
r = roles.setdefault(role, {}).setdefault(t.type_name, {"layers": set(), "bytes": 0, "n": 0})
|
||||
r["layers"].add(layer)
|
||||
r["bytes"] += t.expected_bytes() or 0
|
||||
r["n"] += 1
|
||||
if role.startswith("routed"):
|
||||
per_layer.setdefault(layer, {})[role.split()[1]] = t.type_name
|
||||
break
|
||||
return {"roles": roles, "per_layer": per_layer}
|
||||
|
||||
|
||||
def render(name: str, s: dict) -> str:
|
||||
lines = [f"### {name}", "", "| Role | Format | Layers | Tensors | GiB |", "|---|---|---|---:|---:|"]
|
||||
for role, _ in ROLES:
|
||||
for ty, r in sorted(s["roles"].get(role, {}).items(), key=lambda kv: -kv[1]["bytes"]):
|
||||
lay = "-" if r["layers"] == {-1} else ranges([x for x in r["layers"] if x >= 0])
|
||||
lines.append(f"| {role} | {ty} | {lay} | {r['n']} | {r['bytes'] / 2**30:.2f} |")
|
||||
exp = sum(r["bytes"] for role in ("routed gate", "routed up", "routed down")
|
||||
for r in s["roles"].get(role, {}).values())
|
||||
lines += ["", f"Routed experts: {exp / 2**30:.1f} GiB.", ""]
|
||||
combos: dict[tuple, list[int]] = {}
|
||||
for layer, d in s["per_layer"].items():
|
||||
combos.setdefault((d.get("gate"), d.get("up"), d.get("down")), []).append(layer)
|
||||
lines += ["| Routed gate / up / down | Layers |", "|---|---|"]
|
||||
for (g, u, dn), lay in sorted(combos.items(), key=lambda kv: -len(kv[1])):
|
||||
lines.append(f"| {g} / {u} / {dn} | {ranges(lay)} |")
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("paths", nargs="*")
|
||||
ap.add_argument("--hf", nargs=3, metavar=("REPO", "REV", "DIR"))
|
||||
ap.add_argument("--name")
|
||||
ap.add_argument("--json")
|
||||
a = ap.parse_args()
|
||||
if a.hf:
|
||||
heads = hf_headers(*a.hf)
|
||||
name = a.name or a.hf[2]
|
||||
else:
|
||||
files = sorted({p for g in a.paths for p in glob.glob(g)})
|
||||
heads = [G.GGUFFile(pathlib.Path(p)) for p in files]
|
||||
name = a.name or (pathlib.Path(files[0]).parent.name if files else "?")
|
||||
s = summarize(heads)
|
||||
sys.stdout.write(render(name, s))
|
||||
if a.json:
|
||||
js = {"roles": {r: {t: {"layers": sorted(v["layers"]), "bytes": v["bytes"], "n": v["n"]}
|
||||
for t, v in d.items()} for r, d in s["roles"].items()},
|
||||
"per_layer": {str(k): v for k, v in sorted(s["per_layer"].items())}}
|
||||
pathlib.Path(a.json).write_text(json.dumps(js, indent=1))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,379 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The quant quality yardstick (MODEL-UPDATE.md, Phase 0): teacher-forced top-1 agreement and KL of a quant against
|
||||
Q8_0, on one fixed text set (data/quant_quality/v1: code, docs, English, other languages, an agent transcript).
|
||||
|
||||
python tools/quant_quality.py ids --tokenizer DIR [--set data/quant_quality/v1] [--out set.ids.json]
|
||||
tokenizes the set (each segment cut to --seg-tokens, default 1000) - the ids file is committed with the set
|
||||
(data/quant_quality/v1/set.ids.json), so a box without the tokenizer scores the same positions
|
||||
python tools/quant_quality.py run --config CFG.json --out RUN.tsv [--ids set.ids.json] [--env K=V ...] [--gpu-experts]
|
||||
one `strata --serve` engine (the config's exe and args), every segment one request whose tokens are all read
|
||||
through the decode windows (--short-read), where STRATA_LOGPOS / STRATA_LOGPOS_TOPK=64 write, per position,
|
||||
the log-probability of the text's next token and the 64 most likely tokens. Fixed: the experts on the CPU
|
||||
(one VRAM slot, --expert-cache 1: the verify windows need a profile-filled tier, so the config must have
|
||||
--expert-profile; --gpu-experts: 1500 slots), no expert adaptation, no PCIe share, no suffix drafts, no prompt
|
||||
cache, FP16 K/V, STRATA_ROUTE_TAIL_SKIP=0, STRATA_PREFILL_CPU_SHARE=0. RUN.tsv + RUN.tsv.seg.json (line ranges).
|
||||
python tools/quant_quality.py compare REF.tsv RUN.tsv [...] (REF = the Q8_0 run)
|
||||
per segment and overall: top-1 agreement (same argmax), mean / p99 KL(REF || RUN) over REF's 64 most likely
|
||||
tokens (both renormalized to that set; a token RUN does not list gets RUN's 64th log-probability), and the
|
||||
perplexity of the text under each.
|
||||
|
||||
The RUN.tsv rows are the engine's STRATA_LOGPOS format: pos, target id, logp(target), argmax id, logp(argmax),
|
||||
argmax==target, logp(<|im_end|>), logp(target without <|im_end|>), then 64 `id:logp` fields (natural log).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
HERE = pathlib.Path(__file__).resolve().parent
|
||||
SET_DIR = HERE.parent / "data" / "quant_quality" / "v1"
|
||||
SEGMENTS = ["code", "docs", "english", "multilingual", "agent"]
|
||||
TOPK = 64
|
||||
FIXED = ["--expert-cache", "1", "--adapt-every", "100000", "--pcie-frac", "0", "--suffix-draft", "0",
|
||||
"--prompt-cache", "0", "--kv", "fp16"]
|
||||
FIXED_ENV = {"STRATA_ROUTE_TAIL_SKIP": "0", "STRATA_PREFILL_CPU_SHARE": "0", "STRATA_PCIE_FRAC_DEFAULT": "old"}
|
||||
# config args the yardstick replaces (value-taking) or drops (flags)
|
||||
DROP_VALUE = {"--expert-cache", "--adapt-every", "--pcie-frac", "--suffix-draft", "--prompt-cache", "--max-context",
|
||||
"--prefill", "--prompt-cache-every", "--short-read", "--conversation-cache-mib", "--eos-ids",
|
||||
"--resident-budget-gib", "--kv", "--kv-resident"}
|
||||
DROP_FLAG = {"--serve", "--vision", "--resident-experts", "--resident-cpu-experts"}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ ids
|
||||
def cmd_ids(a) -> int:
|
||||
sys.path.insert(0, str(HERE))
|
||||
import strata_tokenizer as ST # noqa: E402
|
||||
tp = pathlib.Path(a.tokenizer)
|
||||
vocab = json.loads((tp / "vocab.json").read_text(encoding="utf-8"))
|
||||
toks = [None] * len(vocab)
|
||||
for t, i in vocab.items():
|
||||
toks[i] = t
|
||||
tok = ST.Tokenizer(toks, (tp / "merges.txt").read_text(encoding="utf-8").split("\n"),
|
||||
json.loads((tp / "token_type.json").read_text()))
|
||||
segs = []
|
||||
for name in SEGMENTS:
|
||||
text = (pathlib.Path(a.set) / f"{name}.txt").read_text(encoding="utf-8")
|
||||
ids = tok.encode(text, parse_special=(name == "agent"))
|
||||
if len(ids) < a.seg_tokens:
|
||||
raise SystemExit(f"{name}: only {len(ids)} tokens (< {a.seg_tokens})")
|
||||
segs.append({"name": name, "ids": ids[:a.seg_tokens]})
|
||||
print(f"{name}: {len(ids)} tokens, kept {a.seg_tokens}")
|
||||
out = pathlib.Path(a.out or (pathlib.Path(a.set) / "set.ids.json"))
|
||||
out.write_text(json.dumps({"version": pathlib.Path(a.set).name, "seg_tokens": a.seg_tokens, "segments": segs}))
|
||||
print(f"wrote {out}")
|
||||
return 0
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ run
|
||||
def mem_available_gb() -> float:
|
||||
try:
|
||||
for line in open("/proc/meminfo"):
|
||||
if line.startswith("MemAvailable:"):
|
||||
return int(line.split()[1]) / 1048576
|
||||
except OSError:
|
||||
pass
|
||||
return float("inf")
|
||||
|
||||
|
||||
def engine_args(cfg: dict, gpu_experts: bool, seg_tokens: int) -> list[str]:
|
||||
base, out, i = list(cfg["args"]), [], 0
|
||||
while i < len(base):
|
||||
x = base[i]
|
||||
if x in DROP_FLAG:
|
||||
i += 1
|
||||
continue
|
||||
if x in DROP_VALUE:
|
||||
i += 2
|
||||
continue
|
||||
out.append(x)
|
||||
i += 1
|
||||
fixed = list(FIXED)
|
||||
if gpu_experts:
|
||||
fixed[1] = "1500"
|
||||
return [cfg["exe"], "--serve", *out, *fixed, "--max-context", str(seg_tokens + 512),
|
||||
"--short-read", str(seg_tokens + 64), "--prefill", "512"]
|
||||
|
||||
|
||||
def cmd_run(a) -> int:
|
||||
cfg = json.load(open(a.config, encoding="utf-8-sig"))
|
||||
st = json.load(open(a.ids))
|
||||
out = pathlib.Path(a.out).resolve()
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
if out.exists():
|
||||
out.unlink()
|
||||
env = dict(os.environ)
|
||||
env.update(cfg.get("env", {}))
|
||||
if cfg.get("lib_dirs"):
|
||||
env["LD_LIBRARY_PATH"] = ":".join(cfg["lib_dirs"] + [env.get("LD_LIBRARY_PATH", "")])
|
||||
env.update(FIXED_ENV)
|
||||
for kv in a.env or []:
|
||||
k, _, v = kv.partition("=")
|
||||
env[k] = v
|
||||
env["STRATA_LOGPOS"] = str(out)
|
||||
env["STRATA_LOGPOS_TOPK"] = str(TOPK)
|
||||
if mem_available_gb() < a.min_free_gb:
|
||||
raise SystemExit(f"only {mem_available_gb():.0f} GB available (< {a.min_free_gb}): not starting an engine")
|
||||
args = engine_args(cfg, a.gpu_experts, st["seg_tokens"])
|
||||
if a.wrap:
|
||||
args = a.wrap.split() + args
|
||||
errf = open(str(out) + ".stderr.txt", "w")
|
||||
print("engine:", " ".join(args), flush=True)
|
||||
p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=errf, text=True,
|
||||
cwd=cfg.get("cwd"), env=env, bufsize=1)
|
||||
for line in p.stdout:
|
||||
if line.startswith("READY"):
|
||||
break
|
||||
else:
|
||||
raise SystemExit(f"the engine ended before READY (exit {p.wait()}); see {out}.stderr.txt")
|
||||
segs, info = [], []
|
||||
|
||||
def lines() -> int:
|
||||
return sum(1 for _ in open(out)) if out.exists() else 0
|
||||
|
||||
for s in st["segments"]:
|
||||
n0, t0 = lines(), time.time()
|
||||
p.stdin.write("GEN 1 " + ",".join(map(str, s["ids"])) + "\n")
|
||||
p.stdin.flush()
|
||||
done = None
|
||||
for line in p.stdout:
|
||||
if line.startswith(("DONE", "ERR")):
|
||||
done = line.strip()
|
||||
break
|
||||
if done is None or not done.startswith("DONE") or "nonfinite" in done:
|
||||
p.kill()
|
||||
raise SystemExit(f"{s['name']}: the engine answered {done!r}; see {out}.stderr.txt")
|
||||
n1 = lines()
|
||||
segs.append({"name": s["name"], "first_line": n0, "end_line": n1})
|
||||
info.append(f"{s['name']}: {n1 - n0} positions, {time.time() - t0:.1f} s")
|
||||
print(info[-1], flush=True)
|
||||
if n1 - n0 < len(s["ids"]) // 2:
|
||||
p.kill()
|
||||
raise SystemExit(f"{s['name']}: only {n1 - n0} positions were scored (the prompt took the batched path?)")
|
||||
p.stdin.write("QUIT\n")
|
||||
p.stdin.flush()
|
||||
try:
|
||||
p.wait(timeout=600)
|
||||
except subprocess.TimeoutExpired:
|
||||
p.kill()
|
||||
errf.close()
|
||||
err = pathlib.Path(str(out) + ".stderr.txt").read_text(errors="replace")
|
||||
cache = [l for l in err.splitlines() if "expert cache" in l][:3]
|
||||
pathlib.Path(str(out) + ".seg.json").write_text(json.dumps({"segments": segs, "config": a.config,
|
||||
"args": args, "env": a.env or [],
|
||||
"expert_cache_lines": cache}, indent=1))
|
||||
return 0
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ prompt path
|
||||
PROMPT_LENS = (256, 512, 768, 1000)
|
||||
|
||||
|
||||
def cmd_prompt(a) -> int:
|
||||
"""The batched prompt path's answer: every segment's first 256 / 512 / 768 / 1000 tokens as a prompt (one request
|
||||
each, no prompt cache), and the logits after it (STRATA_DUMP_FIRST_LOGITS: float32, the whole vocabulary)."""
|
||||
cfg = json.load(open(a.config, encoding="utf-8-sig"))
|
||||
st = json.load(open(a.ids))
|
||||
out = pathlib.Path(a.out).resolve()
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
for f in out.glob("first.*"):
|
||||
f.unlink()
|
||||
env = dict(os.environ)
|
||||
env.update(cfg.get("env", {}))
|
||||
if cfg.get("lib_dirs"):
|
||||
env["LD_LIBRARY_PATH"] = ":".join(cfg["lib_dirs"] + [env.get("LD_LIBRARY_PATH", "")])
|
||||
env.update(FIXED_ENV)
|
||||
for kv in a.env or []:
|
||||
k, _, v = kv.partition("=")
|
||||
env[k] = v
|
||||
env["STRATA_DUMP_FIRST_LOGITS"] = str(out / "first")
|
||||
if mem_available_gb() < a.min_free_gb:
|
||||
raise SystemExit(f"only {mem_available_gb():.0f} GB available (< {a.min_free_gb}): not starting an engine")
|
||||
args = engine_args(cfg, a.gpu_experts, max(PROMPT_LENS))
|
||||
k = args.index("--short-read")
|
||||
del args[k:k + 2] # the default (64): these prompts take the batched prompt path
|
||||
k = args.index("--prefill")
|
||||
args[k + 1] = "auto"
|
||||
if a.wrap:
|
||||
args = a.wrap.split() + args
|
||||
errf = open(out / "stderr.txt", "w")
|
||||
print("engine:", " ".join(args), flush=True)
|
||||
p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=errf, text=True,
|
||||
cwd=cfg.get("cwd"), env=env, bufsize=1)
|
||||
for line in p.stdout:
|
||||
if line.startswith("READY"):
|
||||
break
|
||||
else:
|
||||
raise SystemExit(f"the engine ended before READY (exit {p.wait()}); see {out}/stderr.txt")
|
||||
index = []
|
||||
for s in st["segments"]:
|
||||
for n in PROMPT_LENS:
|
||||
p.stdin.write("GEN 1 " + ",".join(map(str, s["ids"][:n])) + "\n")
|
||||
p.stdin.flush()
|
||||
done = None
|
||||
for line in p.stdout:
|
||||
if line.startswith(("DONE", "ERR")):
|
||||
done = line.strip()
|
||||
break
|
||||
if done is None or not done.startswith("DONE") or "nonfinite" in done:
|
||||
p.kill()
|
||||
raise SystemExit(f"{s['name']} {n}: the engine answered {done!r}")
|
||||
index.append({"segment": s["name"], "tokens": n})
|
||||
p.stdin.write("QUIT\n")
|
||||
p.stdin.flush()
|
||||
try:
|
||||
p.wait(timeout=600)
|
||||
except subprocess.TimeoutExpired:
|
||||
p.kill()
|
||||
errf.close()
|
||||
(out / "index.json").write_text(json.dumps({"requests": index, "args": args, "env": a.env or []}, indent=1))
|
||||
print(f"{len(index)} prompts")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_pcompare(a) -> int:
|
||||
import numpy as np
|
||||
ref = pathlib.Path(a.ref)
|
||||
idx = json.loads((ref / "index.json").read_text())["requests"]
|
||||
|
||||
def logp(d, i):
|
||||
x = np.fromfile(d / f"first.{i}", dtype=np.float32).astype(np.float64)
|
||||
x -= x.max()
|
||||
return x - np.log(np.exp(x).sum())
|
||||
|
||||
print(f"reference: {ref}")
|
||||
for run in a.runs:
|
||||
r = pathlib.Path(run)
|
||||
kls, agree = [], 0
|
||||
for i in range(len(idx)):
|
||||
if not (r / f"first.{i}").exists():
|
||||
continue
|
||||
lr, la = logp(ref, i), logp(r, i)
|
||||
pr = np.exp(lr)
|
||||
kls.append(float((pr * (lr - la)).sum()))
|
||||
agree += int(lr.argmax() == la.argmax())
|
||||
kls.sort()
|
||||
n = len(kls)
|
||||
print(f"{r.name:40s} prompts {n:3d} top-1 {100 * agree / max(n, 1):6.2f}% KL mean {sum(kls) / max(n, 1):.5f} "
|
||||
f"median {kls[n // 2] if n else float('nan'):.5f} max {kls[-1] if n else float('nan'):.5f}")
|
||||
return 0
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ compare
|
||||
def read_run(path: str) -> dict:
|
||||
rows = open(path).read().splitlines()
|
||||
segs = json.load(open(path + ".seg.json"))["segments"]
|
||||
out = {}
|
||||
for s in segs:
|
||||
d = {}
|
||||
for line in rows[s["first_line"]:s["end_line"]]:
|
||||
f = line.split("\t")
|
||||
if len(f) < 8 + TOPK:
|
||||
continue
|
||||
d[int(f[0])] = (int(f[1]), float(f[2]), int(f[3]), [(int(x), float(y)) for x, y in
|
||||
(z.split(":") for z in f[8:8 + TOPK])])
|
||||
out[s["name"]] = d
|
||||
return out
|
||||
|
||||
|
||||
def compare(ref: dict, run: dict) -> dict:
|
||||
res, allk, tot = {}, [], {"n": 0, "agree": 0, "nll_r": 0.0, "nll_a": 0.0, "kl": 0.0}
|
||||
for name, rr in ref.items():
|
||||
ra = run.get(name, {})
|
||||
pos = sorted(set(rr) & set(ra))
|
||||
n = agree = 0
|
||||
kls, nll_r, nll_a = [], 0.0, 0.0
|
||||
for q in pos:
|
||||
tr, lr, topr, kr = rr[q]
|
||||
ta, la, topa, ka = ra[q]
|
||||
if tr != ta:
|
||||
raise SystemExit(f"{name} pos {q}: target {tr} != {ta} (not the same text)")
|
||||
n += 1
|
||||
agree += topr == topa
|
||||
nll_r -= lr
|
||||
nll_a -= la
|
||||
da = dict(ka)
|
||||
floor = min(b for _, b in ka)
|
||||
pr = [math.exp(b) for _, b in kr]
|
||||
pa = [math.exp(da.get(i, floor)) for i, _ in kr]
|
||||
sr, sa = sum(pr), sum(pa)
|
||||
kls.append(sum((x / sr) * math.log((x / sr) / (y / sa)) for x, y in zip(pr, pa) if x > 0))
|
||||
allk += kls
|
||||
if n:
|
||||
res[name] = {"positions": n, "top1": agree / n, "kl": sum(kls) / n,
|
||||
"ppl_ref": math.exp(nll_r / n), "ppl": math.exp(nll_a / n)}
|
||||
tot["n"] += n
|
||||
tot["agree"] += agree
|
||||
tot["nll_r"] += nll_r
|
||||
tot["nll_a"] += nll_a
|
||||
tot["kl"] += sum(kls)
|
||||
n = max(tot["n"], 1)
|
||||
allk.sort()
|
||||
res["all"] = {"positions": tot["n"], "top1": tot["agree"] / n, "kl": tot["kl"] / n,
|
||||
"kl_p99": allk[int(0.99 * (len(allk) - 1))] if allk else float("nan"),
|
||||
"ppl_ref": math.exp(tot["nll_r"] / n), "ppl": math.exp(tot["nll_a"] / n)}
|
||||
return res
|
||||
|
||||
|
||||
def cmd_compare(a) -> int:
|
||||
ref = read_run(a.ref)
|
||||
print(f"reference: {a.ref}")
|
||||
print(f"{'run':40s} {'segment':13s} {'pos':>5s} {'top1':>7s} {'KL':>8s} {'KL p99':>8s} {'PPL':>7s} {'PPL ref':>7s}")
|
||||
allres = {}
|
||||
for path in a.runs:
|
||||
r = compare(ref, read_run(path))
|
||||
allres[path] = r
|
||||
for seg, v in r.items():
|
||||
if seg != "all" and not a.segments:
|
||||
continue
|
||||
print(f"{pathlib.Path(path).name[:40]:40s} {seg:13s} {v['positions']:5d} {100 * v['top1']:6.2f}% "
|
||||
f"{v['kl']:8.5f} {v.get('kl_p99', float('nan')):8.4f} {v['ppl']:7.3f} {v['ppl_ref']:7.3f}")
|
||||
if a.json:
|
||||
pathlib.Path(a.json).write_text(json.dumps(allres, indent=1))
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
p = sub.add_parser("ids")
|
||||
p.add_argument("--tokenizer", required=True)
|
||||
p.add_argument("--set", default=str(SET_DIR))
|
||||
p.add_argument("--seg-tokens", type=int, default=1000)
|
||||
p.add_argument("--out")
|
||||
p = sub.add_parser("run")
|
||||
p.add_argument("--config", required=True)
|
||||
p.add_argument("--out", required=True)
|
||||
p.add_argument("--ids", default=str(SET_DIR / "set.ids.json"))
|
||||
p.add_argument("--env", action="append")
|
||||
p.add_argument("--gpu-experts", action="store_true", help="--expert-cache 1500 instead of one slot (the experts on the GPU kernels)")
|
||||
p.add_argument("--min-free-gb", type=float, default=16)
|
||||
p.add_argument("--wrap", help="a command prefix for the engine, e.g. 'systemd-run --user --scope -p MemoryMax=200G'")
|
||||
p = sub.add_parser("prompt", help="the batched prompt path's next-token logits after 20 prompts (a directory)")
|
||||
p.add_argument("--config", required=True)
|
||||
p.add_argument("--out", required=True)
|
||||
p.add_argument("--ids", default=str(SET_DIR / "set.ids.json"))
|
||||
p.add_argument("--env", action="append")
|
||||
p.add_argument("--gpu-experts", action="store_true")
|
||||
p.add_argument("--min-free-gb", type=float, default=16)
|
||||
p.add_argument("--wrap")
|
||||
p = sub.add_parser("compare")
|
||||
p.add_argument("ref")
|
||||
p.add_argument("runs", nargs="+")
|
||||
p.add_argument("--segments", action="store_true")
|
||||
p.add_argument("--json")
|
||||
p = sub.add_parser("pcompare", help="full-vocabulary KL and top-1 of `prompt` directories against a reference one")
|
||||
p.add_argument("ref")
|
||||
p.add_argument("runs", nargs="+")
|
||||
a = ap.parse_args()
|
||||
return {"ids": cmd_ids, "run": cmd_run, "prompt": cmd_prompt, "compare": cmd_compare,
|
||||
"pcompare": cmd_pcompare}[a.cmd](a)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+26
-12
@@ -58,14 +58,22 @@ FALLBACK_MODELS = {
|
||||
"with little else running", "download_gb": 83.6, "ram_gb": 62, "arena_gb": 50.3},
|
||||
"IQ1_M": {"about": "the Coder's only size: half the experts, stored like IQ3_S (3.5 bits)", "download_gb": 58.4,
|
||||
"ram_gb": 32, "arena_gb": 23.4, "families": ("coder",)},
|
||||
"UD-Q4_K_XL": {"about": "4-bit (Unsloth Dynamic), EXPERIMENTAL: the best quality, but most experts come from the "
|
||||
"SSD on a 64 GB PC (7-8.5 tokens/s measured)", "download_gb": 111.3, "ram_gb": 48,
|
||||
"arena_gb": 77.0, "families": ("unsloth",), "budget": True, "experimental": True,
|
||||
"vision": True}, # #967: images allowed (setup warns: untested with this file)
|
||||
"UD-IQ4_XS": {"about": "~4-bit i-quant (Unsloth Dynamic), between IQ3_S and UD-Q4_K_XL in quality; on a PC with "
|
||||
"less than ~80 GB of RAM part of its experts are read from the SSD",
|
||||
"download_gb": 93.7, "ram_gb": 48, "arena_gb": 59.5, "families": ("unsloth",), "budget": True,
|
||||
"vision": True},
|
||||
"UD-Q4_K_XL": {"about": "4-bit (Unsloth Dynamic): K-quant experts, between UD-IQ4_XS and UD-Q5_K_XL in quality",
|
||||
"download_gb": 111.3, "ram_gb": 48, "arena_gb": 77.0, "families": ("unsloth",), "budget": True,
|
||||
"vision": True}, # #967: images allowed (setup warns: untested with this file)
|
||||
"UD-Q5_K_XL": {"about": "5-bit (Unsloth Dynamic): Q5_K experts with Q8_0 downs, close to Q8_0 in quality",
|
||||
"download_gb": 158.3, "ram_gb": 108, "arena_gb": 98.4, "families": ("unsloth",), "budget": True,
|
||||
"vision": True},
|
||||
"UD-Q6_K_XL": {"about": "6-bit (Unsloth Dynamic): Q6_K experts with Q8_0 downs",
|
||||
"download_gb": 169.2, "ram_gb": 118, "arena_gb": 109.2, "families": ("unsloth",), "budget": True,
|
||||
"vision": True},
|
||||
"Q8_0": {"about": "8-bit, the reference quality (every expert Q8_0); for a 192 GB PC",
|
||||
"download_gb": 188.2, "ram_gb": 136, "arena_gb": 128.3, "families": ("unsloth",), "budget": True,
|
||||
"vision": True},
|
||||
}
|
||||
FALLBACK_FAMILIES = {
|
||||
"qwen": {"title": "Qwen3.8-Flash-Next", "about": "the original model", "tag": ""},
|
||||
@@ -73,9 +81,9 @@ FALLBACK_FAMILIES = {
|
||||
"authors' numbers)", "tag": "swift-"},
|
||||
"coder": {"title": "Qwen3.8-Flash-Next Coder", "about": "half the experts (code, tools, images kept): needs ~32 GB "
|
||||
"of RAM, faster; weaker outside coding", "tag": "coder-"},
|
||||
"unsloth": {"title": "Qwen3.8-Flash-Next (Unsloth)", "about": "UD-IQ4_XS: a 94 GB download; with less than ~80 GB "
|
||||
"of RAM part of its experts are read from the SSD "
|
||||
"(UD-Q4_K_XL, 111 GB: experimental)",
|
||||
"unsloth": {"title": "Qwen3.8-Flash-Next (Unsloth)", "about": "UD-IQ4_XS (94 GB download) to Q8_0 (188 GB): every "
|
||||
"expert in RAM from ~80 GB (UD-IQ4_XS) to ~136 GB "
|
||||
"(Q8_0) of RAM, else part of them read from the SSD",
|
||||
"tag": "unsloth-", "vision": False},
|
||||
}
|
||||
FALLBACK_CONTEXTS = [8192, 32768, 65536, 131072, 204800, 262144, 393216, 524288]
|
||||
@@ -712,10 +720,14 @@ class Strata:
|
||||
if ram is not None:
|
||||
verdict = "fits" if ram >= d["ram_gb"] else "tight" if ram >= d["ram_gb"] - 8 else "does not fit"
|
||||
try:
|
||||
if d.get("budget"):
|
||||
if d.get("budget") and S and hasattr(S, "unsloth_budget") and not S.unsloth_budget(m, ram):
|
||||
verdict = ("experimental: " if d.get("experimental") else "") + "fits (all of its experts in RAM)"
|
||||
elif d.get("budget"):
|
||||
verdict = (("experimental: " if d.get("experimental") else "")
|
||||
+ "part of its experts in RAM, the rest read from the SSD"
|
||||
if ram >= d["ram_gb"] else "does not fit")
|
||||
if ram >= d["ram_gb"] else
|
||||
"slow here: part of its experts in RAM, the rest read from the SSD (setup "
|
||||
"asks first)" if ram >= 48 else "does not fit")
|
||||
elif S and S.low_ram_needed(m, ram) and S.low_ram_fits(m, ram, vram):
|
||||
verdict = "fits in the low-RAM mode (slower: the GPU holds part of the experts)"
|
||||
except Exception: # noqa: BLE001
|
||||
@@ -960,8 +972,9 @@ def tool_defs(models: dict, families: dict, contexts: list) -> list:
|
||||
"family": {"type": "string", "enum": list(families),
|
||||
"description": "qwen = Qwen3.8-Flash-Next (the original), swift = Swift 1.5 (thinks "
|
||||
"shorter), coder = the Coder (half the experts, ~32 GB RAM, for code), "
|
||||
"unsloth = Unsloth's ~4-bit (UD-IQ4_XS; UD-Q4_K_XL is "
|
||||
"experimental), part of the experts read from the SSD"},
|
||||
"unsloth = Unsloth's 4- to 8-bit files (UD-IQ4_XS, UD-Q4_K_XL, UD-Q5_K_XL, "
|
||||
"UD-Q6_K_XL, Q8_0): every expert in RAM where they fit, else part of them read "
|
||||
"from the SSD"},
|
||||
"model": {"type": "string", "enum": list(models),
|
||||
"description": "the size (quantization): see strata_models"},
|
||||
"context": {"type": "integer", "enum": contexts,
|
||||
@@ -1231,7 +1244,8 @@ class Tools:
|
||||
usable = [g for g in hw.get("gpus", []) if g.get("usable")]
|
||||
vram = max((g["vram_gb"] for g in usable), default=12)
|
||||
context = 32768 if vram < 14 else 65536 if vram < 20 else 131072
|
||||
if models[model].get("budget"):
|
||||
if models[model].get("budget") and (not hasattr(s.setup_module(), "unsloth_budget") or
|
||||
s.setup_module().unsloth_budget(model, hw.get("ram_gb") or 0.0)):
|
||||
context = 8192 if vram < 14 else 32768
|
||||
if vision in ("yes", "gpu", "cpu") and models[model].get("vision", families[family].get("vision")) is False:
|
||||
raise ToolError(f"images are not available with {families[family]['title']} {model} yet: use vision=no")
|
||||
|
||||
@@ -122,7 +122,7 @@ class GgufDirUnsupported(unittest.TestCase):
|
||||
self.assertEqual(msg, "Qwen3.8-Flash-Next-UD-IQ3_XXS-00001-of-00003.gguf is UD-IQ3_XXS, a GGUF Strata "
|
||||
"cannot run")
|
||||
self.assertIn("ISTA-DASLab's GSQ-RCO files", hint)
|
||||
self.assertIn("Unsloth's UD-Q4_K_XL and UD-IQ4_XS only", hint)
|
||||
self.assertIn("Unsloth's UD-IQ4_XS, UD-Q4_K_XL, UD-Q5_K_XL, UD-Q6_K_XL and Q8_0 only", hint)
|
||||
|
||||
def test_a_folder_without_the_choice_names_what_is_there(self):
|
||||
gsq = ["Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-%05d-of-00002.gguf" % i for i in (1, 2)]
|
||||
@@ -145,7 +145,7 @@ class GgufDirUnsupported(unittest.TestCase):
|
||||
code, out, _, _ = install(ram, found, ["--gguf-dir", d, "--family", "unsloth", "--model", "IQ3_XXS"])
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("has no IQ3_XXS model file", out)
|
||||
self.assertIn("choose one of: UD-IQ4_XS, UD-Q4_K_XL (or IQ3_XXS: --family qwen --model IQ3_XXS, --family swift --model "
|
||||
self.assertIn("choose one of: UD-IQ4_XS, UD-Q4_K_XL, UD-Q5_K_XL, UD-Q6_K_XL, Q8_0 (or IQ3_XXS: --family qwen --model IQ3_XXS, --family swift --model "
|
||||
"IQ3_XXS)", out)
|
||||
self.assertIn("Strata runs ISTA-DASLab's GSQ-RCO files", out)
|
||||
|
||||
|
||||
@@ -188,11 +188,11 @@
|
||||
"--mtp",
|
||||
"<T>/data/mtp/rt",
|
||||
"--max-context",
|
||||
"32768",
|
||||
"131072",
|
||||
"--kv",
|
||||
"int8",
|
||||
"--resident-budget-gib",
|
||||
"71"
|
||||
"--kv-resident",
|
||||
"32768"
|
||||
],
|
||||
"cwd": "<T>",
|
||||
"exe": "<T>/engine/<EXE>",
|
||||
@@ -1040,11 +1040,11 @@
|
||||
"--mtp",
|
||||
"<T>/data/mtp/rt",
|
||||
"--max-context",
|
||||
"32768",
|
||||
"65536",
|
||||
"--kv",
|
||||
"int8",
|
||||
"--resident-budget-gib",
|
||||
"71"
|
||||
"--kv-resident",
|
||||
"32768"
|
||||
],
|
||||
"cwd": "<T>",
|
||||
"exe": "<T>/engine/<EXE>",
|
||||
|
||||
@@ -91,12 +91,12 @@ class ExactArch(unittest.TestCase):
|
||||
|
||||
def test_matches_the_engines_header(self):
|
||||
"""include/strata/kernels/gfx_arch.hpp is the reference: gfx1151 has the WMMA kernels and the gfx1151 defaults;
|
||||
gfx1103 and gfx1152 are outside its list."""
|
||||
gfx1103 (Radeon 780M/760M, 0.1.44) shares the gfx11 WMMA kernels; gfx1152 is outside the list."""
|
||||
hpp = (ROOT / "include/strata/kernels/gfx_arch.hpp").read_text(encoding="utf-8")
|
||||
wmma = re.search(r"gfx_arch_is_gfx11_wmma.*?\n}", hpp, re.S).group(0)
|
||||
listed = set(re.findall(r'"(gfx\d+)"', wmma))
|
||||
self.assertIn("gfx1151", listed)
|
||||
self.assertNotIn("gfx1103", listed)
|
||||
self.assertIn("gfx1103", listed) # 0.1.44: the 780M runs the gfx11 WMMA kernels (decode x1.53)
|
||||
self.assertNotIn("gfx1152", listed)
|
||||
self.assertIn('gfx_arch_is(gcn, "gfx1151")', hpp)
|
||||
self.assertEqual(setup.STRIX_HALO_ARCH, "gfx1151")
|
||||
|
||||
+159
-23
@@ -26,6 +26,12 @@ M = "UD-Q4_K_XL"
|
||||
REV = "38bb39ee97821de2c9009abb7e93950eec396e66"
|
||||
|
||||
|
||||
def budget_mode():
|
||||
"""The RAM-budget mode whatever the RAM (MODEL-UPDATE Phase 2 writes it only where the experts do not fit): for the
|
||||
tests of the budget's own paths on PCs that would now keep every expert in RAM (as in sergqwer's fork)."""
|
||||
return mock.patch.object(setup, "unsloth_budget", lambda *a, **k: True)
|
||||
|
||||
|
||||
class Pins(unittest.TestCase):
|
||||
def test_the_four_shards(self):
|
||||
fam = setup.FAMILIES["unsloth"]
|
||||
@@ -37,7 +43,7 @@ class Pins(unittest.TestCase):
|
||||
self.assertEqual(fam["hf"].format(q=M),
|
||||
f"https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF/resolve/{REV}/UD-Q4_K_XL/")
|
||||
self.assertEqual(setup.MODELS[M]["families"], ("unsloth",)) # no other family lists it
|
||||
self.assertTrue(setup.MODELS[M]["experimental"]) # 0.1.39: per model, not the family
|
||||
self.assertFalse(setup.MODELS[M].get("experimental")) # MODEL-UPDATE Phase 2: official
|
||||
self.assertFalse(fam.get("experimental"))
|
||||
self.assertEqual(list(setup.FAMILIES)[0], "qwen") # not the default choice
|
||||
|
||||
@@ -213,7 +219,7 @@ class Main(Base):
|
||||
def test_install(self):
|
||||
code, out, cfg = self.main(["--context", "8192"])
|
||||
self.assertEqual(code, 0, out)
|
||||
self.assertIn("EXPERIMENTAL", out)
|
||||
self.assertNotIn("EXPERIMENTAL", out)
|
||||
base = f"https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF/resolve/{REV}/UD-Q4_K_XL/"
|
||||
self.assertEqual(self.downloads, [base + n for n in setup.UNSLOTH_SHARDS]) # no image encoder
|
||||
self.assertEqual([v[0] for v in self.verified], list(setup.UNSLOTH_SHARDS))
|
||||
@@ -238,6 +244,7 @@ class Main(Base):
|
||||
self.assertEqual(code, 0, out)
|
||||
self.assertEqual(cfg["args"][cfg["args"].index("--max-context") + 1], "8192")
|
||||
|
||||
@budget_mode()
|
||||
def test_more_ram_bigger_budget(self):
|
||||
code, out, cfg = self.main(["--context", "8192"], ram=95.8)
|
||||
self.assertEqual(code, 0, out)
|
||||
@@ -265,18 +272,15 @@ class Main(Base):
|
||||
self.assertIn("--model UD-IQ4_XS --yes", out) # the way to insist (0.1.39: the family's default size)
|
||||
self.assertEqual(self.downloads, [])
|
||||
|
||||
def test_amd_is_asked_before_the_download(self):
|
||||
"""#429: UD-Q4_K_XL has not run on AMD (CUDA-only prompt kernels): --yes alone stops before the 111 GB
|
||||
download, saying why; it is not refused outright (the owner's rule: --model with --yes goes on)."""
|
||||
def test_amd_is_not_asked(self):
|
||||
"""#429 is closed by MODEL-UPDATE Phase 2: UD-Q4_K_XL ran on an R9700 (quality yardstick, decode and prompt
|
||||
numbers in docs/QUANTS.md), so AMD is no longer asked before the download."""
|
||||
r9700 = [{"index": 0, "name": "AMD Radeon AI PRO R9700", "vram_gb": 31.9, "arch": "gfx1201",
|
||||
"driver": "amdgpu"}]
|
||||
# chosen in the menu (2 = UD-Q4_K_XL, after the regular UD-IQ4_XS), not by --model: the answer is no
|
||||
code, out, cfg = self.main(["--context", "8192", "--backend", "hip", "--vision", "no"], model=False,
|
||||
amd=r9700, answers={"Which size": "2", "Try it anyway": "n"})
|
||||
self.assertEqual(code, 1, out)
|
||||
self.assertIn("has not been run on AMD cards yet", out)
|
||||
self.assertIn("--model UD-Q4_K_XL --yes", out)
|
||||
self.assertEqual(self.downloads, [])
|
||||
with mock.patch.object(setup, "get_prebuilt_hip", lambda *a, **k: self.t / "engine"), mock.patch.object(setup, "build_engine_hip", lambda *a, **k: self.t / "engine"):
|
||||
code, out, cfg = self.main(["--context", "8192", "--backend", "hip", "--vision", "no"], amd=r9700)
|
||||
self.assertNotIn("has not been run on AMD cards yet", out)
|
||||
self.assertIn("RAM budget: 40 GiB of UD-Q4_K_XL's experts", out)
|
||||
|
||||
def test_resumed_download_needs_room_for_the_rest_only(self):
|
||||
"""#425: the disk check counts the finished shards and .part files already there (sizes scaled down: a
|
||||
@@ -346,6 +350,7 @@ class Main(Base):
|
||||
self.assertNotIn("--mmap-experts", cfg["args"])
|
||||
self.assertFalse(any("--experts-bin" in r for r in self.runs))
|
||||
|
||||
@budget_mode()
|
||||
@mock.patch.object(setup, "MIN_ENGINE", (0, 1, 39)) # before RESIDENT_SPLIT_ENGINE: no budget on a split
|
||||
def test_split_when_the_ram_holds_it(self):
|
||||
# #498: 165 GiB and --gpus 0,1: the split without the RAM budget (the engine refuses the pair)
|
||||
@@ -359,6 +364,7 @@ class Main(Base):
|
||||
self.assertIn("OS file cache", out)
|
||||
self.assertNotIn("RAM budget: ", out)
|
||||
|
||||
@budget_mode()
|
||||
@mock.patch.object(setup, "MIN_ENGINE", (0, 1, 39)) # before RESIDENT_SPLIT_ENGINE: no budget on a split
|
||||
def test_split_without_the_ram_is_a_warning_not_a_wall(self):
|
||||
# #737: below the worst-case estimate (a 128 GB PC ran it) the split is still the user's call
|
||||
@@ -376,6 +382,7 @@ class Main(Base):
|
||||
self.assertEqual(cfg["gpu"], [0, 1])
|
||||
self.assertNotIn("--resident-budget-gib", cfg["args"])
|
||||
|
||||
@budget_mode()
|
||||
@mock.patch.object(setup, "MIN_ENGINE", (0, 1, 39)) # before RESIDENT_SPLIT_ENGINE: no budget on a split
|
||||
def test_an_explicit_budget_keeps_one_gpu(self):
|
||||
code, out, cfg = self.main(["--context", "8192", "--gpus", "0,1", "--resident-budget-gib", "60"], n_gpus=2,
|
||||
@@ -417,6 +424,7 @@ class Main(Base):
|
||||
self.assertEqual(cfg["gpu"], [0, 1])
|
||||
self.assertIn("--resident-budget-gib", cfg["args"])
|
||||
|
||||
@budget_mode()
|
||||
def test_yes_alone_keeps_one_gpu(self):
|
||||
code, out, cfg = self.main(["--context", "8192"], n_gpus=2, ram=165.0)
|
||||
self.assertEqual(code, 0, out)
|
||||
@@ -446,7 +454,8 @@ class IQ4XS(Base):
|
||||
self.assertEqual(fam["sha256"][n], setup.UNSLOTH_SHARDS[n])
|
||||
self.assertAlmostEqual(setup.MODELS[X]["download_gb"], 93682584224 / 1e9, places=1)
|
||||
self.assertEqual(setup.MODELS[X]["families"], ("unsloth",))
|
||||
self.assertEqual([m for m in setup.MODELS if "unsloth" in setup.MODELS[m].get("families", ())], [M, X])
|
||||
self.assertEqual([m for m in setup.MODELS if "unsloth" in setup.MODELS[m].get("families", ())],
|
||||
[X, M, "UD-Q5_K_XL", "UD-Q6_K_XL", "Q8_0"])
|
||||
self.assertIsNone(setup.gguf_unsupported(names[0])) # #444: a file setup runs now
|
||||
self.assertEqual(setup.gguf_choice(names[0]), ("unsloth", X))
|
||||
self.assertEqual(setup.budget_model({"args": ["--native", "/m/" + names[0]]}), X)
|
||||
@@ -488,21 +497,21 @@ class IQ4XS(Base):
|
||||
self.assertEqual((ch["family"], ch["model"]), ("unsloth", X))
|
||||
|
||||
def test_family_default_and_menus(self):
|
||||
"""The first menu lists the Unsloth family without [experimental]; its size menu puts UD-IQ4_XS first (the
|
||||
default, Enter) and UD-Q4_K_XL second, still marked EXPERIMENTAL; --model names are unchanged."""
|
||||
"""The first menu lists the Unsloth family without [experimental]; its size menu lists the five files by size,
|
||||
UD-IQ4_XS first (the default on 64 GB, Enter), none marked EXPERIMENTAL; --model names are unchanged."""
|
||||
code, out, cfg = self.main(["--context", "8192", "--vision", "no"], version="0.1.38", model=False,
|
||||
family=False, answers={"Which model": "4"}, m=X)
|
||||
self.assertEqual(code, 0, out)
|
||||
fam_line = next(ln for ln in out.splitlines() if ln.startswith(" 4) "))
|
||||
self.assertIn("Qwen3.8-Flash-Next (Unsloth)", fam_line)
|
||||
self.assertIn("UD-IQ4_XS: a 94 GB download", fam_line)
|
||||
self.assertIn("UD-IQ4_XS (94 GB download) to Q8_0", fam_line)
|
||||
self.assertNotIn("[experimental]", out)
|
||||
size_lines = [ln for ln in out.splitlines() if ln.startswith((" 1) UD-", " 2) UD-"))]
|
||||
self.assertEqual(len(size_lines), 2, out)
|
||||
self.assertTrue(size_lines[0].startswith(" 1) UD-IQ4_XS ~4-bit"), size_lines[0])
|
||||
self.assertNotIn("EXPERIMENTAL", size_lines[0])
|
||||
self.assertTrue(size_lines[1].startswith(" 2) UD-Q4_K_XL 4-bit"), size_lines[1])
|
||||
self.assertIn("EXPERIMENTAL", size_lines[1])
|
||||
size_lines = [ln for ln in out.splitlines()
|
||||
if any(ln.startswith(f" {i}) {m} ") for i in range(1, 6) for m in setup.MODELS)]
|
||||
self.assertEqual(len(size_lines), 5, out)
|
||||
for i, (line, m) in enumerate(zip(size_lines, (X, M, "UD-Q5_K_XL", "UD-Q6_K_XL", "Q8_0")), 1):
|
||||
self.assertTrue(line.startswith(f" {i}) {m} "), line)
|
||||
self.assertNotIn("EXPERIMENTAL", line)
|
||||
self.assertTrue(any("Which size" in q and "[1]" in q for q in self.asked), self.asked)
|
||||
self.assertEqual(cfg["model_name"], "qwen3.8-flash-next-unsloth-ud-iq4_xs")
|
||||
code, out, cfg = self.main(["--context", "8192"], version="0.1.38", model=False, m=X) # --yes: same default
|
||||
@@ -530,7 +539,7 @@ class IQ4XS(Base):
|
||||
line = next(ln for ln in out.splitlines() if ln.strip().startswith(X))
|
||||
self.assertIn("fits with 40 GiB of its experts in RAM", line)
|
||||
self.assertNotIn("EXPERIMENTAL", line)
|
||||
self.assertIn("EXPERIMENTAL", next(ln for ln in out.splitlines() if ln.strip().startswith(M)))
|
||||
self.assertNotIn("EXPERIMENTAL", next(ln for ln in out.splitlines() if ln.strip().startswith(M)))
|
||||
|
||||
def test_check_below_every_floor(self):
|
||||
# #977: 16 GB fits no size; the RAM line is not [ok] and the verdict says so
|
||||
@@ -614,6 +623,7 @@ class LayerSplit(unittest.TestCase):
|
||||
from test_setup_golden import card
|
||||
self.found = [card(i, "NVIDIA GeForce RTX 3090", 24.0, "86") for i in range(2)]
|
||||
|
||||
@budget_mode()
|
||||
def test_asked_one_gpu_by_default(self):
|
||||
from test_setup_golden import install
|
||||
argv = ["--family", "unsloth", "--model", M, "--context", "32768", "--no-start"]
|
||||
@@ -706,5 +716,131 @@ class LayerSplit(unittest.TestCase):
|
||||
self.assertIn("--resident-budget-gib", cfg["args"])
|
||||
|
||||
|
||||
Q5, Q6, Q8 = "UD-Q5_K_XL", "UD-Q6_K_XL", "Q8_0"
|
||||
|
||||
|
||||
class Resident(Base):
|
||||
"""MODEL-UPDATE Phase 2 (sergqwer's fork, 0.1.42-nvfp4.2): every expert of an Unsloth file in RAM (a pinned arena, no
|
||||
--resident-budget-gib) where they fit with UNSLOTH_RESIDENT_BESIDE_GB more; the budget below that, when asked for,
|
||||
and on a unified-memory APU."""
|
||||
|
||||
def test_the_rule(self):
|
||||
self.assertEqual(setup.UNSLOTH_RESIDENT_BESIDE_GB, 16)
|
||||
need = {m: setup.MODELS[m]["arena_gb"] / 1.073741824 + 16 for m in (X, M, Q5, Q6, Q8)}
|
||||
self.assertEqual({m: round(v, 1) for m, v in need.items()},
|
||||
{X: 71.4, M: 87.7, Q5: 107.6, Q6: 117.7, Q8: 135.5})
|
||||
for m in (X, M, Q5, Q6, Q8): # "ram_gb" of the bigger files is that need, so below it setup asks
|
||||
if m in (Q5, Q6, Q8):
|
||||
self.assertEqual(setup.MODELS[m]["ram_gb"], int(-(-need[m] // 1)))
|
||||
for ram, budget in ((63.7, {X, M, Q5, Q6, Q8}), (80.0, {M, Q5, Q6, Q8}), (95.8, {Q5, Q6, Q8}),
|
||||
(127.8, {Q8}), (191.0, set())):
|
||||
for m in (X, M, Q5, Q6, Q8):
|
||||
self.assertEqual(setup.unsloth_budget(m, ram), m in budget, (m, ram))
|
||||
self.assertTrue(setup.unsloth_budget(X, 124.0, {"uma": True})) # #1715: measured on discrete cards only
|
||||
self.assertTrue(setup.unsloth_budget(M, 127.2, None, 40)) # --resident-budget-gib: asked for
|
||||
self.assertFalse(setup.unsloth_budget(M, 127.2, {"uma": False}))
|
||||
|
||||
def test_install_at_128_gb(self):
|
||||
for m, ver in ((M, "0.1.32"), (X, "0.1.38"), (Q5, "0.1.44")):
|
||||
with self.subTest(m):
|
||||
code, out, cfg = self.main(["--context", "131072"], ram=127.8, version=ver, m=m)
|
||||
self.assertEqual(code, 0, out)
|
||||
args = cfg["args"]
|
||||
for flag in ("--resident-budget-gib", "--mmap-experts", "--resident-experts", "--low-ram"):
|
||||
self.assertNotIn(flag, args)
|
||||
self.assertIn(f"of {m}'s experts in RAM (they and 16 GiB more fit", out)
|
||||
self.assertNotIn("RAM budget:", out)
|
||||
self.assertEqual(args[args.index("--max-context") + 1], "131072")
|
||||
|
||||
def test_64_gb_keeps_the_budget(self):
|
||||
for m, ver in ((M, "0.1.32"), (X, "0.1.38")):
|
||||
with self.subTest(m):
|
||||
code, out, cfg = self.main(["--context", "8192"], ram=63.7, version=ver, m=m)
|
||||
self.assertEqual(code, 0, out)
|
||||
self.assertEqual(cfg["args"][cfg["args"].index("--resident-budget-gib") + 1], "40")
|
||||
self.assertIn(f"RAM budget: 40 GiB of {m}'s experts in RAM", out)
|
||||
|
||||
def test_an_asked_budget_is_kept(self):
|
||||
code, out, cfg = self.main(["--context", "8192", "--resident-budget-gib", "40"], ram=127.8)
|
||||
self.assertEqual(code, 0, out)
|
||||
self.assertEqual(cfg["args"][cfg["args"].index("--resident-budget-gib") + 1], "40")
|
||||
self.assertNotIn(f"of {M}'s experts in RAM (they and", out)
|
||||
|
||||
def test_the_menu_and_check_say_so(self):
|
||||
code, out, _ = self.main(["--check"], ram=127.8)
|
||||
for m, verdict in ((X, "fits (all of its experts in RAM)"), (M, "fits (all of its experts in RAM)"),
|
||||
(Q5, "fits (all of its experts in RAM)"), (Q8, "slow here: 104 GiB of its 119 GiB")):
|
||||
line = next(ln for ln in out.splitlines() if ln.strip().startswith(m + " "))
|
||||
self.assertIn(verdict, line)
|
||||
|
||||
def test_default_is_the_largest_that_fits(self):
|
||||
for ram, best in ((63.7, X), (95.8, M), (127.8, Q6), (191.0, Q8)):
|
||||
with self.subTest(ram):
|
||||
code, out, cfg = self.main(["--context", "8192"], ram=ram, version="0.1.44", model=False, m=best)
|
||||
self.assertEqual(code, 0, out)
|
||||
self.assertEqual(cfg["model_name"], f"qwen3.8-flash-next-unsloth-{best.lower()}")
|
||||
|
||||
def test_two_gpus_split_with_every_expert_in_ram(self):
|
||||
"""Where the experts fit, two cards are the GGUF models' layer split (no budget question, no #498 note)."""
|
||||
code, out, cfg = self.main(["--context", "8192"], n_gpus=2, ram=127.8)
|
||||
self.assertEqual(code, 0, out)
|
||||
self.assertEqual(cfg["gpu"], [0, 1])
|
||||
self.assertEqual(cfg["layer_split"], "auto")
|
||||
self.assertNotIn("--resident-budget-gib", cfg["args"])
|
||||
self.assertNotIn("which GPUs?", out)
|
||||
|
||||
|
||||
class BigFiles(Base):
|
||||
"""MODEL-UPDATE: UD-Q5_K_XL, UD-Q6_K_XL and Q8_0 - six pinned shards each (sizes and SHA-256 from the Hub), the same
|
||||
GGUF-in-place setup as UD-Q4_K_XL (--compat-bf16 pack, every expert in RAM where it fits); below the all-in-RAM need
|
||||
setup asks first (default no) and says how much is read from the SSD."""
|
||||
|
||||
def test_pins(self):
|
||||
fam = setup.FAMILIES["unsloth"]
|
||||
for m, total in ((Q5, 158286406650), (Q6, 169165382688), (Q8, 188225033248)):
|
||||
names = [setup.model_file(fam, m, i) for i in range(1, setup.model_shards(fam, m) + 1)]
|
||||
self.assertEqual(len(names), 6)
|
||||
self.assertEqual(sum(setup.UNSLOTH_BIG_SHARDS[n][0] for n in names), total)
|
||||
for n in names:
|
||||
self.assertRegex(fam["sha256"][n][1], r"^[0-9a-f]{64}$")
|
||||
self.assertIsNone(setup.gguf_unsupported(names[0]))
|
||||
self.assertEqual(setup.gguf_choice(names[0]), ("unsloth", m))
|
||||
self.assertEqual(setup.budget_model({"args": ["--native", "/m/" + names[0]]}), m)
|
||||
self.assertAlmostEqual(setup.MODELS[m]["download_gb"], total / 1e9, places=1)
|
||||
for i in (2, 3): # the head and the PLE table: the same bytes in all three
|
||||
self.assertEqual(len({setup.UNSLOTH_BIG_SHARDS[setup.model_file(fam, m, i)] for m in (Q5, Q6, Q8)}), 1)
|
||||
|
||||
def test_install_q8_at_192_gb(self):
|
||||
code, out, cfg = self.main(["--context", "32768"], ram=191.0, version="0.1.44", m=Q8)
|
||||
self.assertEqual(code, 0, out)
|
||||
base = f"https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF/resolve/{REV}/Q8_0/"
|
||||
names = [setup.model_file(setup.FAMILIES["unsloth"], Q8, i) for i in range(1, 7)]
|
||||
self.assertEqual(self.downloads, [base + n for n in names])
|
||||
self.assertEqual([v[0] for v in self.verified], names)
|
||||
packs = [r for r in self.runs if r[1].endswith("iq_pack.py")]
|
||||
self.assertIn("--compat-bf16", packs[0])
|
||||
args = cfg["args"]
|
||||
self.assertNotIn("--resident-budget-gib", args)
|
||||
self.assertTrue(args[args.index("--native") + 1].endswith("Q8_0-00001-of-00006.gguf"))
|
||||
self.assertEqual(cfg["model_name"], "qwen3.8-flash-next-unsloth-q8_0")
|
||||
|
||||
def test_q8_below_its_ram_is_asked(self):
|
||||
code, out, cfg = self.main(["--context", "8192"], ram=127.8, version="0.1.44", m=Q8,
|
||||
answers={"Install it anyway": "n"})
|
||||
self.assertEqual(code, 1, out)
|
||||
self.assertIn("Q8_0 needs 136 GB of RAM or more; this PC has 128 GB", out)
|
||||
self.assertEqual(self.downloads, [])
|
||||
code, out, cfg = self.main(["--context", "8192"], ram=127.8, version="0.1.44", m=Q8) # --model + --yes
|
||||
self.assertEqual(code, 0, out)
|
||||
self.assertEqual(cfg["args"][cfg["args"].index("--resident-budget-gib") + 1], "104")
|
||||
|
||||
def test_q5_q6_need_the_q6k_engine(self):
|
||||
for m in (Q5, Q6):
|
||||
code, out, cfg = self.main(["--context", "8192"], ram=191.0, version="0.1.43", m=m)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn(f"{m} needs engine 0.1.44 or newer; this one is 0.1.43", out)
|
||||
self.assertEqual(self.downloads, [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -573,21 +573,26 @@ class Helpers(unittest.TestCase):
|
||||
self.assertEqual(list(S.CONTEXTS), M.FALLBACK_CONTEXTS)
|
||||
|
||||
def test_unsloth_sizes(self):
|
||||
"""0.1.39: UD-IQ4_XS is a regular size, listed first (the family's default); UD-Q4_K_XL stays experimental."""
|
||||
"""0.1.39: UD-IQ4_XS is a regular size, listed first; MODEL-UPDATE Phase 2: UD-Q4_K_XL is no longer experimental,
|
||||
and UD-Q5_K_XL, UD-Q6_K_XL and Q8_0 follow by size."""
|
||||
s = M.Strata(HERE.parent)
|
||||
for models in (s.tables()[0], M.FALLBACK_MODELS):
|
||||
self.assertEqual(s.sizes_of(models, "unsloth"), ["UD-IQ4_XS", "UD-Q4_K_XL"])
|
||||
self.assertEqual(s.sizes_of(models, "unsloth"), ["UD-IQ4_XS", "UD-Q4_K_XL", "UD-Q5_K_XL", "UD-Q6_K_XL", "Q8_0"])
|
||||
self.assertFalse(models["UD-IQ4_XS"].get("experimental"))
|
||||
self.assertTrue(models["UD-Q4_K_XL"].get("experimental"))
|
||||
self.assertFalse(models["UD-Q4_K_XL"].get("experimental"))
|
||||
self.assertEqual(s.sizes_of(M.FALLBACK_MODELS, "qwen"), ["Q2_0", "IQ2_XS", "IQ3_XXS", "IQ3_S"])
|
||||
fam = next(f for f in s.model_table({"ram_gb": 63.7, "gpus": []}) if f["family"] == "unsloth")
|
||||
self.assertFalse(fam["experimental"])
|
||||
self.assertTrue(fam["images"])
|
||||
by = {x["model"]: x for x in fam["sizes"]}
|
||||
self.assertEqual((by["UD-IQ4_XS"]["experimental"], by["UD-IQ4_XS"]["images"]), (False, True))
|
||||
self.assertEqual((by["UD-Q4_K_XL"]["experimental"], by["UD-Q4_K_XL"]["images"]), (True, True)) # #967
|
||||
self.assertEqual((by["UD-Q4_K_XL"]["experimental"], by["UD-Q4_K_XL"]["images"]), (False, True)) # #967
|
||||
self.assertFalse(by["UD-IQ4_XS"]["on_this_pc"].startswith("experimental"))
|
||||
self.assertTrue(by["UD-Q4_K_XL"]["on_this_pc"].startswith("experimental"))
|
||||
self.assertIn("read from the SSD", by["UD-Q4_K_XL"]["on_this_pc"]) # 64 GB: the RAM budget
|
||||
fam = next(f for f in s.model_table({"ram_gb": 127.8, "gpus": []}) if f["family"] == "unsloth")
|
||||
by = {x["model"]: x for x in fam["sizes"]}
|
||||
self.assertEqual(by["UD-Q4_K_XL"]["on_this_pc"], "fits (all of its experts in RAM)")
|
||||
self.assertIn("read from the SSD", by["Q8_0"]["on_this_pc"])
|
||||
|
||||
def test_recommendation_follows_ram(self):
|
||||
s = M.Strata(HERE.parent)
|
||||
|
||||
Reference in new issue
Block a user