jstarks's picture
Upload Nanbeige/Nanbeige4.3-33B WSP + Non-Quantization Shrinking (en90k + drop4-en90k)
0ea0aae verified
Raw History Blame Contribute Delete
13.5 kB
"""Shared raw-byte GGUF streaming utilities for structural shrinking of quantized models.
Copies GGUF KV metadata and streams raw quantized/F32 tensor bytes directly from source
GGUFReader mmaps into GGUFWriter without ever dequantizing or requantizing untouched weights.
"""
from __future__ import annotations
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Tuple
import numpy as np
from gguf import GGMLQuantizationType, GGUFReader, GGUFValueType, GGUFWriter
SKIP_KV_KEYS = frozenset({"GGUF.version", "GGUF.tensor_count", "GGUF.kv_count", "general.architecture"})
def copy_gguf_kv(
reader: GGUFReader,
writer: GGUFWriter,
overrides: Optional[Dict[str, Tuple[Any, GGUFValueType, Optional[GGUFValueType]]]] = None,
) -> None:
"""Copy all metadata KV entries from `reader` into `writer`, applying typed `overrides`."""
ov = dict(overrides or {})
seen = set()
for key, field in reader.fields.items():
if key in SKIP_KV_KEYS:
continue
seen.add(key)
if key in ov:
val, vtype, sub_type = ov[key]
else:
vtype = field.types[0]
sub_type = field.types[1] if len(field.types) > 1 else None
val = field.contents()
if key == "general.alignment":
writer.data_alignment = int(val)
writer.add_key_value(key, val, vtype, sub_type=sub_type)
for key, (val, vtype, sub_type) in ov.items():
if key not in seen and key not in SKIP_KV_KEYS:
writer.add_key_value(key, val, vtype, sub_type=sub_type)
def stream_write_gguf(
out_path: Path,
arch: str,
reader: GGUFReader,
kv_overrides: Optional[Dict[str, Tuple[Any, GGUFValueType, Optional[GGUFValueType]]]],
tensor_specs: Sequence[Tuple[str, Any, Optional[np.ndarray]]],
) -> Path:
"""Stream raw tensor bytes directly to `out_path` without holding the full model in RAM.
Each item in `tensor_specs` is `(dest_name, src_reader_tensor, optional_row_indices)`.
When `optional_row_indices` is provided on a 2D tensor, rows along axis 0 of `src.data`
(the GGML outer dimension `ne[1]`) are selected without dequantization.
"""
out_path.parent.mkdir(parents=True, exist_ok=True)
writer = GGUFWriter(str(out_path), arch, use_temp_file=False)
copy_gguf_kv(reader, writer, overrides=kv_overrides)
for dst_name, src_t, row_idx in tensor_specs:
if src_t.tensor_type == GGMLQuantizationType.F32:
if row_idx is None:
t_shape = tuple(int(x) for x in src_t.data.shape)
nbytes = int(src_t.n_bytes)
else:
t_shape = (len(row_idx), *tuple(int(x) for x in src_t.data.shape[1:]))
nbytes = int(np.prod(t_shape)) * 4
writer.add_tensor_info(dst_name, t_shape, np.dtype(np.float32), nbytes, raw_dtype=None)
elif src_t.tensor_type == GGMLQuantizationType.F16:
if row_idx is None:
t_shape = tuple(int(x) for x in src_t.data.shape)
nbytes = int(src_t.n_bytes)
else:
t_shape = (len(row_idx), *tuple(int(x) for x in src_t.data.shape[1:]))
nbytes = int(np.prod(t_shape)) * 2
writer.add_tensor_info(dst_name, t_shape, np.dtype(np.float16), nbytes, raw_dtype=None)
else:
src_shape = tuple(int(x) for x in src_t.data.shape)
if row_idx is None:
byte_shape = src_shape
nbytes = int(src_t.n_bytes)
else:
assert len(src_shape) == 2, f"Row slicing only supports 2D tensors, got {dst_name} {src_shape}"
row_bytes = int(src_shape[1])
byte_shape = (len(row_idx), row_bytes)
nbytes = len(row_idx) * row_bytes
writer.add_tensor_info(dst_name, byte_shape, np.dtype(np.uint8), nbytes, raw_dtype=src_t.tensor_type)
writer.write_header_to_file()
writer.write_kv_data_to_file()
writer.write_ti_data_to_file()
try:
for dst_name, src_t, row_idx in tensor_specs:
if src_t.tensor_type == GGMLQuantizationType.F32:
arr = np.asarray(src_t.data, dtype=np.float32)
if row_idx is not None:
arr = arr[row_idx]
writer.write_tensor_data(np.ascontiguousarray(arr, dtype=np.float32))
elif src_t.tensor_type == GGMLQuantizationType.F16:
arr = np.asarray(src_t.data, dtype=np.float16)
if row_idx is not None:
arr = arr[row_idx]
writer.write_tensor_data(np.ascontiguousarray(arr, dtype=np.float16))
else:
arr = np.asarray(src_t.data, dtype=np.uint8)
if row_idx is not None:
arr = arr[row_idx]
writer.write_tensor_data(np.ascontiguousarray(arr, dtype=np.uint8))
finally:
writer.close()
return out_path
class ModelServer:
"""Managed `llama-server` launcher parameterized by any GGUF `model_path`."""
def __init__(
self,
model_path: Path,
extra_args: List[str],
lora_paths: Optional[List[str]] = None,
tag: str = "struct_test",
):
import stage_and_sanity_nanbeige as ss
self.ss = ss
self.model_path = Path(model_path)
self.extra_args = list(extra_args)
self.lora_paths = list(lora_paths or [])
self.log_path = self.model_path.parent.parent / f"sanity_{tag}.log"
self.proc = None
self.fp = None
self.startup_s = 0.0
self.vram_before: Dict[str, int] = {}
self.vram_loaded: Dict[str, int] = {}
self.peak_vram_mb: int = 0
def sample_vram(self) -> None:
v = self.ss.vram_mb()["used_mb"]
if v > self.peak_vram_mb:
self.peak_vram_mb = v
def __enter__(self):
import subprocess
import time
self.vram_before = self.ss.vram_mb()
cmd = [
str(self.ss.LLAMA_SERVER),
"-m", str(self.model_path),
"--host", "127.0.0.1",
"--port", str(self.ss.PORT),
"--jinja",
"-np", "1",
"-ngl", "99",
"--fit", "off",
*self.extra_args,
]
if self.lora_paths:
cmd += ["--lora-init-without-apply", "--lora", ",".join(self.lora_paths)]
t0 = time.perf_counter()
self.fp = open(self.log_path, "w", encoding="utf-8", errors="replace")
self.proc = subprocess.Popen(cmd, stdout=self.fp, stderr=subprocess.STDOUT)
deadline = time.time() + 180.0
while time.time() < deadline:
if self.proc.poll() is not None:
self.fp.flush()
tail = self.log_path.read_text(encoding="utf-8", errors="replace")[-1500:]
raise RuntimeError(f"llama-server exited rc={self.proc.returncode}:\n{tail}")
try:
if self.ss.http_get_json(f"{self.ss.BASE_URL}/health", timeout=2.0).get("status") == "ok":
self.startup_s = round(time.perf_counter() - t0, 2)
self.vram_loaded = self.ss.vram_mb()
self.peak_vram_mb = int(self.vram_loaded["used_mb"])
return self
except Exception:
pass
time.sleep(0.4)
self.__exit__(None, None, None)
raise TimeoutError(f"llama-server startup timeout for {self.model_path.name}")
def __exit__(self, *args):
import subprocess
if self.proc is not None and self.proc.poll() is None:
self.proc.terminate()
try:
self.proc.wait(timeout=8)
except subprocess.TimeoutExpired:
self.proc.kill()
self.proc.wait(timeout=5)
self.proc = None
if self.fp is not None:
try:
self.fp.close()
except Exception:
pass
self.fp = None
def run_sanity_probes(srv: ModelServer, include_tool_history: bool = False) -> Dict[str, Any]:
"""Run next-token, 128t speed, QA, weather tool, optional Turn-2 history, and 10-item math sanity."""
import json
import re
import time
ss = srv.ss
out: Dict[str, Any] = {
"startup_s": srv.startup_s,
"vram_loaded": srv.vram_loaded,
"next_token": ss.probe_next_token(),
"speed_128": ss.bench_128_tok(),
}
r1, _ = ss.http_post_json(f"{ss.BASE_URL}/v1/chat/completions", {
"model": "nanbeige",
"messages": [{"role": "user", "content": "What is the capital of France? Answer in one word."}],
"temperature": 0.0,
"max_tokens": 512,
"cache_prompt": False,
})
e1 = ss.extract_nanbeige_response(r1)
out["qa_paris"] = {
"ok": "paris" in e1["content"].lower(),
"content": e1["content"][:160],
"has_reasoning": bool(e1["reasoning"]),
"tok": e1["comp_tok"],
"tps": e1["tps"],
}
t_weather = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather for city",
"parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
},
}]
r2, _ = ss.http_post_json(f"{ss.BASE_URL}/v1/chat/completions", {
"model": "nanbeige",
"messages": [{"role": "user", "content": "What is the weather in Tokyo?"}],
"tools": t_weather,
"temperature": 0.0,
"max_tokens": 512,
"cache_prompt": False,
})
e2 = ss.extract_nanbeige_response(r2)
out["tool_weather"] = {
"ok": bool(e2["parsed_tool_calls"]) and e2["parsed_tool_calls"][0]["name"] == "get_weather",
"parsed": e2["parsed_tool_calls"],
"content": e2["content"][:120],
}
if include_tool_history:
hm_res = {}
for lbl, ud in (("openai_str", False), ("dict_args", True)):
try:
r3, ms3 = ss.http_post_json(f"{ss.BASE_URL}/v1/chat/completions", {
"model": "nanbeige",
"messages": ss.prepare_messages(ss.tasks.HOLDOUT_S5_TURN2_JSON[0]["messages"], use_dict_args=ud),
"tools": ss.tasks.WORKER_TOOLS,
"temperature": 0.0,
"max_tokens": 512,
"cache_prompt": False,
})
e3 = ss.extract_nanbeige_response(r3)
hm_res[lbl] = {"ok": True, "ms": round(ms3, 1), "content": e3["content"][:120]}
except Exception as err:
hm_res[lbl] = {"ok": False, "error": str(err)[:200]}
out["tool_history"] = hm_res
est_cache = json.loads(ss.ESTABLISHED_CACHE.read_text(encoding="utf-8"))
stem_cache = json.loads(ss.STEM_CACHE.read_text(encoding="utf-8"))
items = []
for idx, it in enumerate(est_cache["gsm8k"][:5]):
items.append(("gsm8k", f"gsm8k_{idx}", 1024, f"{it['question']}\nPut your final numerical answer in \\boxed{{}}.", it["answer"].split("####")[-1].strip()))
for idx, it in enumerate(stem_cache["math500_eval"][:5]):
items.append(("math500", f"math_{idx:02d}", 1536, f"Solve the following mathematics problem carefully. Put your final simplified answer inside \\boxed{{}}.\n\n{it['problem']}", str(it["answer"])))
recs = []
t0 = time.time()
for i, (kind, iid, mtok, prompt, gold) in enumerate(items, 1):
raw, _ = ss.http_post_json(f"{ss.BASE_URL}/v1/chat/completions", {
"model": "nanbeige",
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.0,
"max_tokens": mtok,
"cache_prompt": False,
})
ext = ss.extract_nanbeige_response(raw)
if kind == "gsm8k":
pred = ss.extract_boxed(ext["content"]) or ss.extract_boxed(ext["reasoning"])
if not pred:
nums = re.findall(r"-?\d+(?:,\d+)*(?:\.\d+)?", ext["content"] or ext["reasoning"])
pred = nums[-1] if nums else ""
ok = ss.norm_num(pred) == ss.norm_num(gold)
else:
pred = ss._extract_math_answer(ext["content"], ext["reasoning"])
ok = ss._sympy_equiv(pred, gold)
cut = (not ext["content"]) and ext["finish_reason"] == "length"
recs.append({
"id": iid, "kind": kind, "passed": bool(ok), "pred": pred, "gold": gold,
"comp_tok": ext["comp_tok"], "tps": ext["tps"], "cut": cut, "is_loop": ext["is_loop"],
})
el = time.time() - t0
eta = (len(items) - i) * (el / i)
print(
f" [Sanity {i:2d}/{len(items)}] {iid:9s} pass={str(ok):5s} pred={pred!r} gold={gold!r} "
f"tok={ext['comp_tok']} tps={ext['tps']} cut={cut} loop={ext['is_loop']} | ETA={eta:.1f}s",
flush=True,
)
out["sanity_10"] = {
"pass": sum(r["passed"] for r in recs),
"total": len(recs),
"gsm8k": sum(r["passed"] for r in recs if r["kind"] == "gsm8k"),
"math500": sum(r["passed"] for r in recs if r["kind"] == "math500"),
"cutoffs": sum(r["cut"] for r in recs),
"loops": sum(r["is_loop"] for r in recs),
"mean_tps": round(sum(r["tps"] for r in recs if r["tps"] > 0) / max(1, sum(1 for r in recs if r["tps"] > 0)), 1),
"records": recs,
}
return out