File size: 13,497 Bytes
0ea0aae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
"""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