diff --git a/CMakeLists.txt b/CMakeLists.txt index 9debf810..1acade5e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -180,6 +180,7 @@ if(STRATA_ENABLE_CUDA) src/kernels/cuda/kv_stream.cu src/kernels/cuda/kv_q4.cu src/kernels/cuda/fused_gr.cu + src/kernels/cuda/cvec.cu src/kernels/cuda/qsa_decode_attn.cu src/kernels/cuda/fused_gdn.cu src/kernels/cuda/dequant_bf16.cu @@ -369,6 +370,10 @@ if(STRATA_ENABLE_CUDA) target_include_directories(kv_q4_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) target_link_libraries(kv_q4_parity PRIVATE strata_kernels CUDA::cudart) add_test(NAME kv_q4_parity COMMAND kv_q4_parity) + add_executable(cvec_parity src/kernels/cvec_parity.cpp) + target_include_directories(cvec_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + target_link_libraries(cvec_parity PRIVATE strata_kernels CUDA::cudart) + add_test(NAME cvec_parity COMMAND cvec_parity) # Plan v0.3 P3: native MMVQ for 1..8 tokens (bitwise selftest + --bench timing); synthetic data, no model. if(STRATA_BUILD_TESTS) diff --git a/README.md b/README.md index 2b1fd572..d70d44c7 100644 --- a/README.md +++ b/README.md @@ -99,7 +99,10 @@ Not sure? Take **IQ2_XS**. You can add another one later with `START-HERE.bat -- - **Thinking:** the model thinks before it answers. Choose **off, low, medium or high** - in the chat page menu, with `/think low` in `chat.py`, or with your app's "reasoning effort" setting. Off is fastest; high is best for hard questions. - **Pictures:** in the chat page click **Picture**; in `chat.py` type `/image `; in apps just attach them. -- **From your phone or another PC:** see the [details](docs/DETAILS.md#using-it) (set an API key first). +- **From your phone or another PC:** `START-HERE.bat --setup --host 0.0.0.0 --api-key `, then open the + address the server window prints; see the [details](docs/DETAILS.md#using-it). +- **Experimental speed projection (off by default):** an experimental control vector that setup can turn on; it + changes how the model answers - read [what it does](docs/DETAILS.md#experimental-speed-projection-experimental-off-by-default) first. **Good to know:** it answers one request at a time. The first message of a chat is read in full (about 1 minute per 30,000 tokens); after that it keeps the conversation and reads only what is new, so follow-ups start in seconds. diff --git a/bench/results/2026-09-27-esp/README.md b/bench/results/2026-09-27-esp/README.md new file mode 100644 index 00000000..19ff7780 --- /dev/null +++ b/bench/results/2026-09-27-esp/README.md @@ -0,0 +1,36 @@ +# 2026-09-27: the experimental-speed-projection control vector + +The package's `Qwen3.8-Flash-Next-experimental-speed-projection.gguf` (47 unit directions of 2,560, one per layer), +applied as `--control-vector-scaled FILE:1.0 --control-vector-layer-range 4 44 --cvec-mode project --cvec-dir +per-layer`: after layers 4-44, every hyper-connection stream `h -= (h . v) v`. The package describes it as a +refusal-direction projection. Q2_0, RTX 5070, fixed experts (`--expert-cache 4000 --pcie-frac 0 --adapt-swaps 0`). + +## Kernel (`cvec_parity`) + +Project and add against a double-precision reference (max error 5e-7); with the switch off, the kernel's pending +residual write is bitwise the fused hyper-connection read's own, so a loaded-but-off vector is the stock engine. + +## Teacher-forced, stock vs projection (`esp_kl.py`, per-token path) + +| Text | Tokens | Same top-1 | Mean KL | p99 KL | Perplexity stock | With the vector | +|---|---:|---:|---:|---:|---:|---:| +| Code | 511 | 92.8% | 0.098 | 1.69 | 2.594 | 2.982 | +| Document | 1,023 | 89.8% | 0.058 | 0.84 | 30.299 | 30.984 | +| Chat | 1,023 | 89.6% | 0.050 | 0.33 | 18.409 | 18.485 | +| **All** | 2,557 | | **0.063** (max 4.10) | 1.00 | | | + +The package reports a mean KL of 0.186 on its own neutral text with UD-Q2_K_XL in llama.cpp. + +Cost on the same tokens: 44.34 -> 44.26, 46.74 -> 46.56, 47.02 -> 46.83 tok/s (0.2-0.4%). + +## Serve (`esp_serve.py`) + +- Loaded and switched off (`cvec=0`) vs an engine without it: 65 / 65 first tokens after prefixes (verify windows + and the batched prompt path) and three 256-token generations **token-identical**. +- On, off, on again: identical (the switch drops the conversation cache, so nothing computed one way is reused the + other way). +- The prompt paths steer like the per-token path: served-with-vector first tokens agree with the per-token path's + teacher-forced argmax with the vector 62 / 65, and with the stock one 57 / 65 (stock served: 64 / 65 and 57 / 65). +- Decode tok/s of 3 x 256-token generations: stock 66.4, on 76.7 / 81.2. **Not a like-for-like comparison:** the + model writes different text with it on (on the code prompt it copied a long stretch of the source, which prompt + lookup drafts at 91% acceptance, where stock stopped after 78 tokens). On the same tokens it is 0.2-0.4% slower. diff --git a/bench/results/2026-09-27-esp/esp_kl.py b/bench/results/2026-09-27-esp/esp_kl.py new file mode 100644 index 00000000..5ec6d3ad --- /dev/null +++ b/bench/results/2026-09-27-esp/esp_kl.py @@ -0,0 +1,85 @@ +"""Teacher-forced logits, stock vs the experimental-speed-projection vector, on the same texts and fixed experts. + + python esp_kl.py run # the dumps (per-token path) + python esp_kl.py compare # same top-1, mean/median KL(stock || projection), perplexities +""" +import json +import os +import subprocess +import sys + +import numpy as np + +S = os.path.dirname(os.path.abspath(__file__)) +E = r"C:\Users\AI-Server\Desktop\Strata\Public\Engine" +EXE = E + r"\build-dev\strata.exe" +VEC = r"C:\Users\AI-Server\Desktop\Strata\experimental-speed-projection\Qwen3.8-Flash-Next-experimental-speed-projection.gguf" +TEXTS = {"code": S + r"\p512.ids", "doc": S + r"\4k-02-long-doc-1k.ids", "chat": S + r"\4k-04-chat-1k.ids"} +OUT = S + r"\esp-kl" +ARMS = {"stock": [], + "proj": ["--control-vector-scaled", VEC + ":1.0", "--control-vector-layer-range", "4", "44", + "--cvec-mode", "project", "--cvec-dir", "per-layer"]} + + +def base_args(): + c = json.load(open(S + r"\cfg-rel.json")) + a = list(c["args"]) + i = a.index("--expert-cache") + a[i + 1] = "4000" + j = a.index("--prefill") # the prompt one token at a time: a logits row per position + del a[j:j + 2] + return a + ["--pcie-frac", "0", "--adapt-swaps", "0"], c + + +def run(): + os.makedirs(OUT, exist_ok=True) + args, c = base_args() + env = dict(os.environ) + env["PATH"] = os.pathsep.join(c["lib_dirs"]) + os.pathsep + env["PATH"] + for name, path in TEXTS.items(): + for arm, extra in ARMS.items(): + out = f"{OUT}\\{name}-{arm}.bin" + if os.path.exists(out): + continue + cmd = [EXE, *args, *extra, "--tokens-file", path, "--max-new", "1", "--dump-logits", out] + with open(f"{OUT}\\{name}-{arm}.log", "w") as log: + r = subprocess.run(cmd, cwd=c["cwd"], stdout=log, stderr=subprocess.STDOUT, env=env) + print(name, arm, "exit", r.returncode, flush=True) + + +def load(p): + h = np.fromfile(p, dtype=np.int32, count=2) + return np.memmap(p, dtype=np.float32, mode="r", offset=8, shape=(int(h[1]), int(h[0]))) + + +def lsm(x): + x = x.astype(np.float64) + m = x.max(axis=-1, keepdims=True) + return x - (m + np.log(np.exp(x - m).sum(axis=-1, keepdims=True))) + + +def compare(): + print(f"{'text':<6}{'tokens':>7}{'same top-1':>11}{'mean KL':>9}{'median KL':>11}{'p99 KL':>8}{'ppl stock':>10}{'ppl proj':>9}") + allkl = [] + for name, path in TEXTS.items(): + ids = [int(x) for x in open(path).read().replace(",", " ").split()] + a, b = load(f"{OUT}\\{name}-stock.bin"), load(f"{OUT}\\{name}-proj.bin") + n = min(a.shape[0], b.shape[0], len(ids) - 1) + kl, same, la, lb = [], 0, [], [] + for r in range(0, n, 64): + pa, pb = lsm(a[r:min(n, r + 64)]), lsm(b[r:min(n, r + 64)]) + kl += list((np.exp(pa) * (pa - pb)).sum(axis=1)) + same += int((pa.argmax(1) == pb.argmax(1)).sum()) + nxt = np.array(ids[r + 1:min(n, r + 64) + 1]) + la += list(pa[np.arange(len(nxt)), nxt]) + lb += list(pb[np.arange(len(nxt)), nxt]) + kl = np.array(kl) + allkl += list(kl) + print(f"{name:<6}{n:>7}{100 * same / n:>10.1f}%{kl.mean():>9.3f}{np.median(kl):>11.4f}{np.percentile(kl, 99):>8.2f}" + f"{np.exp(-np.mean(la)):>10.3f}{np.exp(-np.mean(lb)):>9.3f}") + allkl = np.array(allkl) + print(f"all {len(allkl)} tokens: mean KL {allkl.mean():.3f}, max {allkl.max():.2f}, p99 {np.percentile(allkl, 99):.2f}") + + +if __name__ == "__main__": + {"run": run, "compare": compare}[sys.argv[1]]() diff --git a/bench/results/2026-09-27-esp/esp_serve.py b/bench/results/2026-09-27-esp/esp_serve.py new file mode 100644 index 00000000..4ec20059 --- /dev/null +++ b/bench/results/2026-09-27-esp/esp_serve.py @@ -0,0 +1,129 @@ +"""Serve-mode checks of the experimental-speed-projection vector (exact mode: fixed experts, no PCIe share). + + python esp_serve.py run ARM # ARM = stock | vec; writes esp-serve/.json + python esp_serve.py compare + +Per arm: the first greedy token after many prefixes of three texts (short ones go through the verify windows, long +ones through the batched prompt path; the conversation cache reuses the earlier prefix), and three 256-token greedy +generations. The vec arm runs everything with cvec=1, then cvec=0, then cvec=1 again. +""" +import json +import os +import sys +import threading + +S = os.path.dirname(os.path.abspath(__file__)) +E = r"C:\Users\AI-Server\Desktop\Strata\Public\Engine" +sys.path.insert(0, E) +from serve.server import StrataEngine # noqa: E402 + +EXE = E + r"\build-dev\strata.exe" +VEC = r"C:\Users\AI-Server\Desktop\Strata\experimental-speed-projection\Qwen3.8-Flash-Next-experimental-speed-projection.gguf" +TEXTS = {"code": S + r"\p512.ids", "doc": S + r"\4k-02-long-doc-1k.ids", "chat": S + r"\4k-04-chat-1k.ids"} +OUT = S + r"\esp-serve" +VEC_ARGS = ["--control-vector-scaled", VEC + ":1.0", "--control-vector-layer-range", "4", "44", + "--cvec-mode", "project", "--cvec-dir", "per-layer"] + + +def ids_of(name): + return [int(x) for x in open(TEXTS[name]).read().replace(",", " ").split()] + + +def engine(extra): + c = json.load(open(S + r"\cfg-rel.json")) + a = list(c["args"]) + a[a.index("--expert-cache") + 1] = "4000" + env = dict(os.environ) + env["PATH"] = os.pathsep.join(c["lib_dirs"]) + os.pathsep + env["PATH"] + return StrataEngine(EXE, a + ["--pcie-frac", "0", "--adapt-swaps", "0"] + extra, cwd=c["cwd"], + log=OUT + r"\engine.log", env=env) + + +def gen(eng, ids, n, sampling): + toks = [t for t in eng.generate(ids, n, sampling, threading.Event()) if t is not None] + return toks, dict(eng.last) + + +def suite(eng, sampling): + out = {"first": {}, "long": {}} + for name in TEXTS: + ids = ids_of(name) + # short prefixes growing by 4 (each continues the live session through the verify windows), then long ones + # SHRINKING (no cached prefix, so each is read from 0 by the batched prompt path) + lens = list(range(32, 72, 4)) + list(range(min(len(ids) - 1, 700), 95, -48)) + out["first"][name] = {L: gen(eng, ids[:L], 1, sampling)[0][0] for L in lens} + for name in TEXTS: + toks, last = gen(eng, ids_of(name)[:300], 256, sampling) + out["long"][name] = {"tokens": toks, "last": last} + return out + + +def run(arm): + os.makedirs(OUT, exist_ok=True) + eng = engine(VEC_ARGS if arm == "vec" else []) + res = {"info": eng.info} + if arm == "stock": + res["stock"] = suite(eng, {}) + else: + res["on"] = suite(eng, {"experimental_speed_projection": True}) + res["off"] = suite(eng, {"experimental_speed_projection": False}) + res["on2"] = suite(eng, {"experimental_speed_projection": True}) + eng.close() + json.dump(res, open(f"{OUT}\\{arm}.json", "w")) + print(arm, "done", eng.info, flush=True) + + +def compare(): + import numpy as np + sys.path.insert(0, S) + from esp_kl import load, OUT as KL + st = json.load(open(OUT + r"\stock.json")) + ve = json.load(open(OUT + r"\vec.json")) + print("engine INFO (vec):", ve["info"]) + + def eq_first(a, b): + tot = same = 0 + for name in a: + for L, t in a[name].items(): + tot += 1 + same += int(b[name][L] == t) + return same, tot + + def eq_long(a, b): + return all(a[n]["tokens"] == b[n]["tokens"] for n in a), \ + [(n, next((i for i, (x, y) in enumerate(zip(a[n]["tokens"], b[n]["tokens"])) if x != y), None)) for n in a] + + print("1. vector loaded, switched off == no vector") + print(" first tokens: %d / %d identical" % eq_first(st["stock"]["first"], ve["off"]["first"])) + print(" 256-token generations identical:", *eq_long(st["stock"]["long"], ve["off"]["long"])) + print("2. repeatable: on, off, on again") + print(" first tokens: %d / %d identical" % eq_first(ve["on"]["first"], ve["on2"]["first"])) + print(" 256-token generations identical:", *eq_long(ve["on"]["long"], ve["on2"]["long"])) + print("3. the prompt paths against the per-token path's teacher-forced argmax (row L-1 predicts token L)") + for arm, first in (("stock", st["stock"]["first"]), ("on", ve["on"]["first"])): + for ref in ("stock", "proj"): + agree = tot = 0 + for name in first: + d = load(f"{KL}\\{name}-{ref}.bin") + for L, t in first[name].items(): + L = int(L) + if L - 1 < d.shape[0]: + tot += 1 + agree += int(int(np.argmax(d[L - 1])) == t) + print(f" served {arm:<5} vs per-token {ref:<5}: {agree} / {tot}") + print("4. how different the text is: 256-token generations, on vs stock, first difference") + print(" ", eq_long(st["stock"]["long"], ve["on"]["long"])[1]) + print("5. decode speed (exact mode: fixed experts, no PCIe share - not the normal setup)") + for label, r in (("stock", st["stock"]), ("vec off", ve["off"]), ("vec on", ve["on"]), ("vec on 2", ve["on2"])): + g = sum(v["last"]["generated"] for v in r["long"].values()) + ms = sum(v["last"]["decode_ms"] for v in r["long"].values()) + acc = sum(v["last"].get("drafts_accepted", 0) for v in r["long"].values()) + off = sum(v["last"].get("drafts_offered", 0) for v in r["long"].values()) + print(f" {label:<9} {g / ms * 1000:6.1f} tok/s drafts accepted {acc}/{off}") + + +if __name__ == "__main__": + if sys.argv[1] == "run": + run(sys.argv[2]) + else: + compare() diff --git a/bench/results/2026-09-27-esp/serve-checks.txt b/bench/results/2026-09-27-esp/serve-checks.txt new file mode 100644 index 00000000..23219a39 --- /dev/null +++ b/bench/results/2026-09-27-esp/serve-checks.txt @@ -0,0 +1,20 @@ +1. vector loaded, switched off == no vector + first tokens: 65 / 65 identical + 256-token generations identical: True [('code', None), ('doc', None), ('chat', None)] +2. repeatable: on, off, on again + first tokens: 65 / 65 identical + 256-token generations identical: True [('code', None), ('doc', None), ('chat', None)] +3. the prompt paths against the per-token path's teacher-forced argmax (row L-1 predicts token L) + served stock vs per-token stock: 64 / 65 + served stock vs per-token proj : 57 / 65 + served on vs per-token stock: 57 / 65 + served on vs per-token proj : 62 / 65 +4. how different the text is: 256-token generations, on vs stock, first difference + [('code', 11), ('doc', 6), ('chat', 3)] +5. decode speed (exact mode: fixed experts, no PCIe share - not the normal setup) + stock 66.4 tok/s drafts accepted 256/309 + vec off 65.7 tok/s drafts accepted 251/318 + vec on 76.7 tok/s drafts accepted 366/425 + vec on 2 81.2 tok/s drafts accepted 366/423 + +[exited with code 0] diff --git a/bench/results/2026-09-27-esp/teacher-forced.txt b/bench/results/2026-09-27-esp/teacher-forced.txt new file mode 100644 index 00000000..5beb4b81 --- /dev/null +++ b/bench/results/2026-09-27-esp/teacher-forced.txt @@ -0,0 +1,6 @@ +text tokens same top-1 mean KL median KL p99 KL ppl stock ppl proj +code 511 92.8% 0.098 0.0031 1.69 2.594 2.982 +doc 1023 89.8% 0.058 0.0271 0.84 30.299 30.984 +chat 1023 89.6% 0.050 0.0265 0.33 18.409 18.485 +all 2557 tokens: mean KL 0.063, max 4.10, p99 1.00 + diff --git a/data/experimental-speed-projection/Qwen3.8-Flash-Next-experimental-speed-projection.gguf b/data/experimental-speed-projection/Qwen3.8-Flash-Next-experimental-speed-projection.gguf new file mode 100644 index 00000000..5c10294a Binary files /dev/null and b/data/experimental-speed-projection/Qwen3.8-Flash-Next-experimental-speed-projection.gguf differ diff --git a/data/experimental-speed-projection/Qwen3.8-Flash-Next-experimental-speed-projection.json b/data/experimental-speed-projection/Qwen3.8-Flash-Next-experimental-speed-projection.json new file mode 100644 index 00000000..82946d62 --- /dev/null +++ b/data/experimental-speed-projection/Qwen3.8-Flash-Next-experimental-speed-projection.json @@ -0,0 +1,26 @@ +{ + "mode": "project", + "dir": "per-layer", + "scale": 1.0, + "layer_range": [ + 4, + 44 + ], + "refusal_harmful_thinkoff": 2.0, + "refusal_harmful_thinkon": 2.0, + "refusal_harmless_thinkoff": 4.0, + "refusal_harmless_thinkon": 6.0, + "broken": 0, + "kl_mean": 0.18598, + "kl_max": 18.26549, + "kl_p99": 3.143571, + "decode_tps": 51.19, + "vector_file": "Qwen3.8-Flash-Next-experimental-speed-projection.gguf", + "base_model_gguf": "unsloth/Qwen3.8-Flash-Next-GGUF UD-Q2_K_XL", + "base_model_sha256_shard1": "a4f3b21e77353999829f2f767e9ac21ce9c71d29a74f2cc9eda48c9bf23c8b86", + "worktree_commit": "37e026e3b", + "criterion_status": "PASS", + "dirty_direction": false, + "note": "projection ablation h -= s*(h.v)*v, v unit-normalized per layer. dir=per-layer", + "branch": "cvec-hooks (github.com/Cudila/llama.cpp)" +} diff --git a/data/experimental-speed-projection/README.md b/data/experimental-speed-projection/README.md new file mode 100644 index 00000000..ad4a0085 --- /dev/null +++ b/data/experimental-speed-projection/README.md @@ -0,0 +1,21 @@ +# experimental-speed-projection (EXPERIMENTAL, off by default) + +`Qwen3.8-Flash-Next-experimental-speed-projection.gguf` is a 480 KB control vector for Qwen3.8-Flash-Next: one unit +direction of 2,560 values per layer (`direction.1` .. `direction.47`, GGUF `controlvector` format). The JSON beside it +is the configuration its authors selected and their scores. + +**What it does.** Turned on, Strata removes each direction from the residual stream after layers 4-44 +(`h -= (h . v) v` on every hyper-connection stream), the same operation as llama.cpp's `--cvec-mode project` in the +package's patches. The package's own documentation describes the vector as a **refusal-direction projection**: the +model declines far fewer requests (it reports 1 of 50 vs 50 of 50 on its test set), and removing refusals removes a +safety behaviour - you are responsible for what the model writes with it on. It also shifts the model's predictions +slightly on ordinary text (measured here: `bench/results/2026-09-27-esp/`). It is not an optimization in the engine: +on the same text it costs 0.2-0.4% per token; a chat's speed with it on depends on the text the model writes. + +**Turning it on.** `START-HERE.bat --setup` asks (default: off), or pass `--experimental-speed-projection on`. With it +loaded, the web app's Sampling drawer and the API field `"experimental_speed_projection": false` switch it off per +request. See `docs/DETAILS.md`, "Experimental speed projection". + +**Origin and license.** A local package of the vector (the published original uses filenames containing "refusal"; +the bytes are the same), made from Qwen3.8-Flash-Next activations, so the Qwen Community License 1.0 of the model +applies to it. Made for the original Qwen3.8-Flash-Next (not Swift 1.5). diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 9b94718a..5d39e404 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -324,6 +324,45 @@ test images. --- +## Experimental speed projection (EXPERIMENTAL, off by default) + +**This is an experiment, not a finished feature.** It ships with Strata but stays off unless you turn it on. + +A 480 KB control vector for Qwen3.8-Flash-Next (`data/experimental-speed-projection/`, see its README). After each +of layers 4-44 the engine removes one direction from every hyper-connection stream of the residual: `h -= (h . v) v`, +one unit vector `v` per layer, exactly as llama.cpp does with the package's `--cvec-mode project` patches. + +**What it changes.** The vector's own package describes it as a **refusal-direction projection**: with it the model +declines far fewer requests (it reports 1 of 50 vs 50 of 50 on its test set), and removing refusals removes a safety +behaviour - you are responsible for what the model writes with it on. It also shifts ordinary answers a little +(measured below). It is not an optimization in the engine: on the same text it costs 0.2-0.4% per token. What a +chat's tokens/s does with it on depends on the text the model writes (length, repetition, how well the drafts land), +so measure it on your own prompts; the Monitor marks every request ESP or stock. + +**Turning it on (at setup).** `START-HERE.bat --setup` asks "Turn on the experimental speed projection?" (default: +no), or pass `--experimental-speed-projection on` (`off`, or a path to another vector GGUF). Only for the original +Qwen3.8-Flash-Next, not Swift 1.5. It writes these engine flags (llama.cpp's) into `strata-.json`: + +``` +--control-vector-scaled \data\experimental-speed-projection\Qwen3.8-Flash-Next-experimental-speed-projection.gguf:1.0 +--control-vector-layer-range 4 44 --cvec-mode project --cvec-dir per-layer +``` + +The engine log then says `control vector mode = project, dir = per-layer, layers 4..44 (41 steered)`, and the web +app's About tab lists it. (`--cvec-mode add` is llama.cpp's stock additive mode, for additive vectors.) + +**Per request.** A loaded vector is on for every request unless it says otherwise: the web app's Sampling drawer has +a switch, and the API takes `"experimental_speed_projection": false` in the request body (OpenAI and Anthropic; a +config default goes in `"sampling": {"experimental_speed_projection": false}`). Switching drops the conversation +cache once, since the model state was computed the other way. Switched off, the output is token-for-token the stock +model's. + +**Measured here** (Q2_0, fixed experts, 2,557 teacher-forced tokens of code, a document and a chat): the top-1 token +changes at 10% of positions, mean KL from the stock model 0.063 nats (max 4.1), perplexity +15% on code, +2.3% on +the document, +0.4% on the chat. Details: `bench/results/2026-09-27-esp/`. + +--- + ## Troubleshooting | Symptom | What to do | diff --git a/include/strata/kernels/cvec.hpp b/include/strata/kernels/cvec.hpp new file mode 100644 index 00000000..2dd120fc --- /dev/null +++ b/include/strata/kernels/cvec.hpp @@ -0,0 +1,56 @@ +// include/strata/kernels/cvec.hpp - a control vector on the residual stream: the engine's side of llama.cpp's +// `llama_adapter_cvec` with the `--cvec-mode` / `--cvec-dir` extension of the `experimental-speed-projection` +// package (its `02-cvec-projection-mode.patch`, and `01-qwen4exp-cvec-hooks.patch` for WHERE it applies). +// +// After layer l's FFN write - llama.cpp's `build_cvec(res_hc, il)` right after the layer's second +// `build_hc_combine` - every one of the hc residual streams h of every token becomes +// +// project: h <- h - s_l (h . v_l) v_l v_l = d / |d|, s_l = |d|, d = the scaled direction +// add: h <- h + d llama.cpp's stock additive control vector +// +// for l in [first, last]. `d` is the GGUF's `direction.` times the file's scale (summed over files), with +// src = l (per-layer) or one fixed layer (single:L, project mode only), exactly as llama.cpp's loader places it; +// layer 0 has no direction. Off unless a vector is loaded (--control-vector-scaled); a loaded one is switched +// per request through a device flag, so the captured graphs are the same either way. With the flag off the +// result is bit-identical to the engine without a vector: the kernel then only applies the pending residual +// write, with the fused read's own arithmetic. +#pragma once + +#include +#include +#include + +namespace strata::kernels { + +struct Cvec { + const float* dir = nullptr; ///< device, n_layers * n_embd: project = the unit v_l, add = d_l; zero rows elsewhere + const float* s = nullptr; ///< device, n_layers: project = s_l, add = 1; 0 = the layer is not steered + const int* on = nullptr; ///< device int: 0 = this request runs the stock model + int mode = 0; ///< 0 = project, 1 = add + int first = 0, last = -1; ///< the steered layers, inclusive + int64_t n_embd = 0, hc = 0; + bool loaded() const { return dir != nullptr; } + /// Layer l's FFN write is followed by the vector (with a real direction there). Decided at load time, never + /// per request: it changes where the residual write happens, so the graphs depend on it. + bool covers(int64_t l) const { return loaded() && l >= first && l <= last && l < (int64_t) steered.size() && steered[(size_t) l]; } + std::vector steered; ///< host copy of s_l != 0 +}; + +/// The loaded vector (empty until `cvec_upload`). +const Cvec& cvec(); + +/// Upload a vector built by the loader: `dir` is n_layers * n_embd, `s` n_layers (see `Cvec`). Starts ON. +bool cvec_upload(const std::vector& dir, const std::vector& s, int mode, int first, int last, + int64_t n_embd, int64_t hc, std::string& err); + +/// The per-request switch. Synchronizes the device when it changes, so call it between requests. +void cvec_set_enabled(bool on); +bool cvec_enabled(); + +/// Layer `layer`'s vector on T tokens' residual stacks (`R + t * r_ld`, hc streams of n_embd). With `write`, the +/// pending FFN write `R += bo * 2 sigmoid(inj / hc)` (the fused read's arithmetic) is applied first, for callers +/// whose writes are folded into the next layer's read; without it, R must already hold the layer's output. +void cvec_apply(float* R, int64_t layer, int64_t T, int64_t r_ld, const float* bo, int64_t bo_ld, const float* inj, + int64_t inj_ld, bool write, void* stream); + +} // namespace strata::kernels diff --git a/serve/server.py b/serve/server.py index 73e7c6f2..7cb57f7e 100644 --- a/serve/server.py +++ b/serve/server.py @@ -160,14 +160,21 @@ class StrataEngine: seed = sampling.get("seed") if isinstance(seed, int) and seed > 0: keys += f" seed={seed}" - return keys + return keys + StrataEngine.projection_key(sampling) + + @staticmethod + def projection_key(sampling: dict) -> str: + """`cvec=0|1`: the experimental-speed-projection control vector for this request, when the engine was + started with one (--control-vector-scaled; an engine without one ignores the key). Absent = on.""" + on = sampling.get("experimental_speed_projection") + return f" cvec={int(on)}" if isinstance(on, bool) else "" def generate(self, ids, max_new, sampling, cancel, embeddings=None): """Yields token ids, and None as a heartbeat every 10 s while the engine is quiet (reading a long prompt): the HTTP layer turns it into an SSE comment, which keeps clients' watchdogs calm and notices a client that has gone. A consumer that stops early (or `cancel`) makes the engine STOP, so it does not run to max_new.""" self.progress = None - head = f"GENI {int(max_new)} {embeddings}" if embeddings else \ + head = f"GENI {int(max_new)}{self.projection_key(sampling or {})} {embeddings}" if embeddings else \ f"GEN {int(max_new)}{self.sampling_keys(sampling or {}) if not embeddings else ''}" self.proc.stdin.write(f"{head} {','.join(str(int(t)) for t in ids)}\n") self.proc.stdin.flush() @@ -562,7 +569,10 @@ class Service: if self.status.get("busy"): last = dict(getattr(self.engine, "last", {}) or {}) started = self.status.get("started", time.time()) + loaded = str((getattr(self.engine, "info", {}) or {}).get("cvec", 0)) not in ("0", "", "None") self.history.append({ + "projection": (sampling or {}).get("experimental_speed_projection") is not False + if loaded else None, "time": started, "duration_s": round(time.time() - started, 1), "finish": finish, "prompt_tokens": len(ids), "reused": last.get("reused"), "output_tokens": n, "prompt_ms": last.get("prompt_ms"), "decode_ms": last.get("decode_ms"), @@ -996,6 +1006,11 @@ def sampling_defaults_from_config(cfg: dict) -> dict: if not number or value != int(value) or value <= 0: raise SystemExit(f"[strata] config sampling.seed={value!r}: expected a positive integer") out[key] = int(value) + elif key == "experimental_speed_projection": + if not isinstance(value, bool): + raise SystemExit(f"[strata] config sampling.experimental_speed_projection={value!r}: expected true or " + "false (the default for requests that leave it out, when the engine has the vector)") + out[key] = value else: print(f"[strata] config sampling.{key}={value!r}: unknown key, ignored", flush=True) return out diff --git a/serve/web/app.js b/serve/web/app.js index 64f546ee..776f0940 100644 --- a/serve/web/app.js +++ b/serve/web/app.js @@ -270,7 +270,8 @@ function renderMonitor(live, hw, st, eng, h, last, requests) { body.innerHTML = requests.slice(0, 12).map((r) => { const [cls, text] = badge[r.finish] || ["", r.finish || "–"]; const t = new Date(r.time * 1000).toLocaleTimeString([], {hour: "2-digit", minute: "2-digit", second: "2-digit"}); - return `${esc(t)}${esc(text)}${fmt(r.prompt_tokens)} + const proj = r.projection == null ? "" : ` ${r.projection ? "ESP" : "stock"}`; + return `${esc(t)}${esc(text)}${proj}${fmt(r.prompt_tokens)} ${fmt(r.reused)}${fmt(r.output_tokens)}${fmt(r.decode_tok_s, 1)} ${fmt(r.duration_s, 1)} s`; }).join(""); @@ -281,6 +282,15 @@ function facts(el, rows) { el.innerHTML = rows.filter((r) => r[1] != null && r[1] !== "").map(([k, v, copy]) => `
${esc(k)}
${copy ? `${esc(v)}` : esc(v)}
`).join(""); } +// INFO cvec=project:4-44[:singleL] | add:A-B | 0 +function projectionText(c) { + if (!c || c === "0" || c === 0) return null; + const [mode, range, single] = String(c).split(":"); + const [a, b] = (range || "").split("-"); + return `${mode === "project" ? "Projection" : "Additive"} control vector on layers ${a}–${b}` + + `${single ? ` (layer ${single.replace("single", "")}'s direction)` : ""}. Per chat in Sampling. Its package ` + + "describes the vector as a refusal-direction projection; measure the speed yourself"; +} function renderAbout(eng, hw, st) { const kv = {int8: "8-bit", q4_0: "4-bit (Hadamard-rotated)", fp16: "16-bit"}[eng.kv] || eng.kv; facts($("facts-engine"), [ @@ -291,6 +301,7 @@ function renderAbout(eng, hw, st) { ["Experts in VRAM", eng.expert_slots ? `${fmt(eng.expert_slots)} (${gb((eng.expert_cache_mib || 0) * 1048576)} GB)` : null], ["Speculation", eng.spec ? `MTP drafts up to ${Math.max(0, (eng.mtp_max || eng.spec) - 1)} tokens${eng.lookup ? ", prompt lookup on" : ""}` : null], ["Images", eng.images ? "on" : "off"], + ["Experimental speed projection", projectionText(eng.cvec)], ]); facts($("facts-hw"), [ ["GPU", st.gpu_name ? `${st.gpu_name}${hw.gpu_mem_total ? `, ${gb(hw.gpu_mem_total, 0)} GB` : ""}` : "not readable (NVML)"], @@ -376,7 +387,7 @@ function markdown(text) { } // ------------------------------------------------------------------ Chat -const DEFAULTS = {thinking: "high", temperature: 0.6, top_p: 0.95, top_k: 20, max: "", seed: "", show: true}; +const DEFAULTS = {thinking: "high", temperature: 0.6, top_p: 0.95, top_k: 20, max: "", seed: "", show: true, esp: true}; let settings = {...DEFAULTS, ...store.get("sampling", {})}; let messages = store.get("chat", []); let attachments = []; // {name, url} @@ -515,6 +526,7 @@ async function send() { } if (settings.seed) body.seed = +settings.seed; if (settings.max) body.max_tokens = +settings.max; + if (projectionLoaded()) body.experimental_speed_projection = !!settings.esp; let firstAt = null, thinkStart = null, usage = null, frame = 0; const paint = () => { frame = 0; updateAssistant(el, m, true); scrollDown(); }; @@ -562,7 +574,8 @@ async function send() { const n = usage ? usage.completion_tokens : null; if (n && firstAt) { const secs = (performance.now() - firstAt) / 1000; - m.meta = `${fmt(n)} tokens${secs > 0.25 ? ` · ${fmt(n / secs, 1)} tok/s` : ""}${m.stopped ? " · stopped" : ""}`; + m.meta = `${fmt(n)} tokens${secs > 0.25 ? ` · ${fmt(n / secs, 1)} tok/s` : ""}${m.stopped ? " · stopped" : ""}` + + (projectionLoaded() ? (settings.esp ? " · projection on" : " · projection off") : ""); } else if (m.stopped) { m.meta = "Stopped"; } @@ -649,8 +662,15 @@ function loadDrawer(s = settings) { $("s-temp").value = s.temperature; $("s-topp").value = s.top_p; $("s-topk").value = s.top_k; $("s-max").value = s.max; $("s-seed").value = s.seed; $("s-show").setAttribute("aria-checked", String(!!s.show)); + $("s-esp").setAttribute("aria-checked", String(s.esp !== false)); + $("esp-row").hidden = !projectionLoaded(); outputs(); } +// the engine was started with the experimental-speed-projection control vector (INFO cvec=...) +function projectionLoaded() { + const c = lastMetrics && lastMetrics.engine ? lastMetrics.engine.cvec : 0; + return !!c && c !== "0"; +} function outputs() { const t = +$("s-temp").value; $("o-temp").textContent = t === 0 ? "0 · greedy" : t.toFixed(2); @@ -663,12 +683,14 @@ function outputs() { for (const b of $("s-thinking").children) b.onclick = () => { for (const x of $("s-thinking").children) x.setAttribute("aria-checked", String(x === b)); outputs(); }; for (const id of ["s-temp", "s-topp", "s-topk"]) $(id).oninput = outputs; $("s-show").onclick = () => $("s-show").setAttribute("aria-checked", String($("s-show").getAttribute("aria-checked") !== "true")); +$("s-esp").onclick = () => $("s-esp").setAttribute("aria-checked", String($("s-esp").getAttribute("aria-checked") !== "true")); $("s-reset").onclick = () => loadDrawer(DEFAULTS); $("s-apply").onclick = () => { const sel = [...$("s-thinking").children].find((b) => b.getAttribute("aria-checked") === "true"); settings = {thinking: sel ? sel.dataset.v : "high", temperature: +$("s-temp").value, top_p: +$("s-topp").value, top_k: +$("s-topk").value, max: $("s-max").value.trim(), seed: $("s-seed").value.trim(), - show: $("s-show").getAttribute("aria-checked") === "true"}; + show: $("s-show").getAttribute("aria-checked") === "true", + esp: $("s-esp").getAttribute("aria-checked") === "true"}; store.set("sampling", settings); openDrawer(false); toast("success", "Sampling saved", settings.temperature === 0 ? "Greedy: the same question gives the same answer." : ""); diff --git a/serve/web/index.html b/serve/web/index.html index 5fc9bec6..150479a9 100644 --- a/serve/web/index.html +++ b/serve/web/index.html @@ -192,6 +192,9 @@
Show thinking
expanded while it streams
+
diff --git a/setup.py b/setup.py index b46653a1..b5b6e010 100644 --- a/setup.py +++ b/setup.py @@ -21,6 +21,8 @@ What the first run does (each step is skipped when it is already done): Options: --family qwen|swift, --model Q2_0|IQ2_XS|IQ3_XXS|IQ3_S, --context 32768, --vision yes|no|gpu|cpu, --port 8080, --yes (recommended answers, no questions), --setup (install another model / change settings instead of starting), --no-start, +--host 0.0.0.0 --api-key KEY (reach it from other devices on your network), --experimental-speed-projection on|off +(EXPERIMENTAL, off by default), --models-dir DIR, --gguf-dir DIR (use GGUF files you already have), --build (compile instead of the ready-made engine), --check (only check this PC). """ @@ -86,6 +88,8 @@ FAMILIES = { "license": "Swift Open License 1.0: https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF"}, } MMPROJ = "mmproj-Qwen3.8-Flash-Next-BF16.gguf" +# EXPERIMENTAL, off by default (setup asks): a control vector shipped with the repository, see its README +ESP_VECTOR = ROOT / "data" / "experimental-speed-projection" / "Qwen3.8-Flash-Next-experimental-speed-projection.gguf" # the image encoder on the GPU (~1.2 GB at 1024 image tokens) warms up before the engine starts, so the engine # sizes its expert slots around it and the default reserve (700 MiB) is enough; engines before 0.1.2 need more VISION = {"gpu": {"max_tokens": 1024, "reserve_mib": 700}, @@ -652,6 +656,9 @@ def main() -> int: "precise)") ap.add_argument("--vision", choices=["yes", "no", "none", "gpu", "cpu"], help="let the model read images (yes = the encoder on the GPU)") + ap.add_argument("--experimental-speed-projection", metavar="on|off|GGUF", + help="EXPERIMENTAL, off by default: the control vector in data/experimental-speed-projection " + "(or another GGUF) as a projection on layers 4-44; see docs/DETAILS.md") ap.add_argument("--port", type=int, default=8080) ap.add_argument("--host", help="where the server listens: 127.0.0.1 = this PC only (default), 0.0.0.0 = also other " "devices on your network (issue #26; set --api-key too)") @@ -784,6 +791,25 @@ def main() -> int: say(" download and keeps ~1.4 GB of VRAM free for the image encoder, so text is a few % slower.") vision = "gpu" if ask("Do you want images?", ["y", "n"], "n", a.yes) == "y" else "none" ok("images: " + {"none": "off", "gpu": "on", "cpu": "on (encoder on the CPU)"}[vision]) + # EXPERIMENTAL: the experimental-speed-projection control vector (data/experimental-speed-projection), off unless + # chosen here; with it loaded, the web app and the API switch it off per request + esp = None + esp_choice = (a.experimental_speed_projection or "").strip() + if family == "qwen": + if not esp_choice: + say() + say(" EXPERIMENTAL - speed projection: a small control vector applied while the model runs (layers 4-44).") + say(" It changes how the model answers: its package describes it as a refusal-direction projection (the") + say(" model declines far fewer requests). Off unless you choose it; when on, the web app can switch it off") + say(" per chat. Details: data/experimental-speed-projection/README.md") + esp_choice = "on" if ask("Turn on the experimental speed projection?", ["y", "n"], "n", a.yes) == "y" else "off" + if esp_choice.lower() not in ("off", "no", "n", "0"): + esp = ESP_VECTOR if esp_choice.lower() in ("on", "yes", "y", "1") else Path(esp_choice).expanduser().resolve() + if not esp.is_file(): + fail(f"the experimental speed projection's vector is missing: {esp}") + ok("experimental speed projection: " + ("ON (experimental)" if esp else "off")) + elif esp_choice.lower() not in ("", "off", "no", "n", "0"): + warn("the experimental speed projection is made for the original Qwen3.8-Flash-Next, not Swift 1.5: left off") models_dir = Path(a.gguf_dir) if a.gguf_dir else Path(a.models_dir) / tag shards = [models_dir / fam["file"].format(q=model, i=i) for i in (1, 2)] have_model = all(s.exists() and (done(s) or a.gguf_dir) for s in shards) @@ -896,6 +922,10 @@ def main() -> int: ok(f"KV streaming on: the context's KV cache lives in RAM ({kv_ram_gb:.1f} GB), more experts fit in VRAM") if vision != "none": args += ["--vision", "--vram-reserve-mib", str(VISION[vision]["reserve_mib"])] + if esp is not None: + # the package's profile, with llama.cpp's flags (the engine takes the same ones) + args += ["--control-vector-scaled", f"{esp}:1.0", "--control-vector-layer-range", "4", "44", + "--cvec-mode", "project", "--cvec-dir", "per-layer"] cfg = {"exe": str(eng / EXE), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"), "model_name": f"{fam['name']}-{model.lower()}", "log": str(ROOT / f"strata-{tag.lower()}.log"), "lib_dirs": lib_dirs, "port": a.port} diff --git a/src/core/layer.cpp b/src/core/layer.cpp index b3c0bc54..b40b9169 100644 --- a/src/core/layer.cpp +++ b/src/core/layer.cpp @@ -25,6 +25,7 @@ #include "strata/kernels/native_rope.hpp" #include "strata/kernels/native_flash_attn.hpp" #include "strata/kernels/fused_gr.hpp" +#include "strata/kernels/cvec.hpp" #include "strata/kernels/qsa_decode_attn.hpp" #include "strata/kernels/fused_gdn.hpp" #include "strata/kernels/qsa_select.hpp" @@ -1107,7 +1108,8 @@ bool block_layer_pre(const WeightTable& tables, const ModelGeometry& g, int64_t // the device half: `ple_block` reading `emb_dev`, and the history shift. const bool fused = g_fused_gr && stage_prefix == 0 && half == 0 && strata::kernels::fused_gr_supported(g.n_embd, g.hc, g.hc_lr); - bool pending_ffn = fused && layer > 0; // layer-1's FFN write has not been applied to R yet + // layer-1's FFN write has not been applied to R yet - unless a control vector follows it, which needs R + bool pending_ffn = fused && layer > 0 && !strata::kernels::cvec().covers(layer - 1); if (ple != nullptr && ple->ready() && layer == 1 && (half == 0 || half == 1)) { if (pending_ffn) { const strata::kernels::GrShapes gs0{g.n_embd, g.hc, g.hc_lr}; @@ -1242,10 +1244,23 @@ st_begin(layer, 5, stream); if (g_shared_early ? !moe_combine_parts(g, layer, k, mb, parts, bb.block_out, stream, err) : !moe_finish(tables, g, layer, k, mb, bb.mixed, parts, bb.block_out, stream, err)) return false; st_end(layer, 5, stream); dump_half(bb, g, layer, bb.block_out, (uint64_t) g.n_embd, g.n_embd, stream); dump_half(bb, g, layer, bb.inject, (uint64_t) 2 * g.n_embd + g.hc, g.hc, stream); st_begin(layer, 6, stream); - if (!(g_fused_gr && strata::kernels::fused_gr_supported(g.n_embd, g.hc, g.hc_lr))) - gr_write(bb.R, bb.block_out, bb.inject, gs, bb.R, stream); - else if (layer == g.n_layers - 1) - gr_write(bb.R, bb.block_out, bb.inject2, gs, bb.R, stream); // materialise R for the head + const bool steer = strata::kernels::cvec().covers(layer); // --control-vector-scaled: after this write + try { + if (!(g_fused_gr && strata::kernels::fused_gr_supported(g.n_embd, g.hc, g.hc_lr))) { + gr_write(bb.R, bb.block_out, bb.inject, gs, bb.R, stream); + if (steer) strata::kernels::cvec_apply(bb.R, layer, 1, g.hc * g.n_embd, nullptr, 0, nullptr, 0, false, stream); + } else if (layer == g.n_layers - 1) { + gr_write(bb.R, bb.block_out, bb.inject2, gs, bb.R, stream); // materialise R for the head + if (steer) strata::kernels::cvec_apply(bb.R, layer, 1, g.hc * g.n_embd, nullptr, 0, nullptr, 0, false, stream); + } else if (steer) { + // the write the next layer's fused read would have folded, then the vector + strata::kernels::cvec_apply(bb.R, layer, 1, g.hc * g.n_embd, bb.block_out, g.n_embd, bb.inject2, g.hc, + true, stream); + } + } catch (const std::exception& e) { + err = std::string("block_layer_post: ") + e.what(); + return false; + } st_end(layer, 6, stream); return true;} bool block_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base, const GdnBuffers& gb, const QsaState& qst, const QsaBuffers& qb, const MoEBuffers& mb, int64_t k, const BlockBuffers& bb, const float* parts, void* stream, std::string& err, const Doorbell* db, const PleRun* ple) { // The two halves back to back. `parts` must be THIS layer's experts and must be ready before the call - diff --git a/src/core/verify.cpp b/src/core/verify.cpp index fd5c8d2f..6762d11a 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -11,6 +11,7 @@ #include "strata/kernels/cpu/expert.hpp" #include "strata/kernels/elementwise.hpp" #include "strata/kernels/fused_gr.hpp" +#include "strata/kernels/cvec.hpp" #include "strata/kernels/gr.hpp" #include "strata/kernels/kv_q4.hpp" #include "strata/kernels/kv_q8.hpp" @@ -331,7 +332,9 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { wi[h] = need(v, (std::string(pfx[h]) + "inject.weight").c_str(), err); if (!wn[h] || !wd[h] || !wu[h] || !wi[h]) return false; } - bool pending = l > 0; // the previous layer's FFN write, folded into this layer's first read + // the previous layer's FFN write, folded into this layer's first read (a control vector after it has + // already applied it) + bool pending = l > 0 && !cvec().covers(l - 1); if (l == 1 && ple_on) { float* normalized = (float*) ((uint8_t*) ss.ple.scratch + ple_block_scratch_bytes()); for (int t = tb; t < te; ++t) { @@ -569,8 +572,12 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { mb.weights = w_ + t * K; mb.shared = shared_ + t * N; if (!moe_combine_parts(g, l, K, mb, parts_ + (size_t) t * K * N, bo_ + t * N, cs, err)) return false; } - if (l == g.n_layers - 1) + if (l == g.n_layers - 1) { for (int t = tb; t < te; ++t) gr_write(Rt(t), bo_ + t * N, inj2_ + t * HC, gs, Rt(t), cs); + if (cvec().covers(l)) cvec_apply(Rt(tb), l, n, HC * N, nullptr, 0, nullptr, 0, false, cs); + } else if (cvec().covers(l)) { + cvec_apply(Rt(tb), l, n, HC * N, bo_ + tb * N, N, inj2_ + tb * HC, HC, true, cs); + } return true; }; diff --git a/src/kernels/cuda/cvec.cu b/src/kernels/cuda/cvec.cu new file mode 100644 index 00000000..87ba141f --- /dev/null +++ b/src/kernels/cuda/cvec.cu @@ -0,0 +1,128 @@ +// src/kernels/cuda/cvec.cu - see include/strata/kernels/cvec.hpp. +#include "strata/kernels/cvec.hpp" + +#include + +#include + +namespace strata::kernels { +namespace { + +constexpr int THREADS = 256; +constexpr int MAXK = 16; // n_embd up to 4096, held in registers between the dot and the update + +Cvec g_cvec; +int* g_on = nullptr; +bool g_on_host = false; + +// the fused hyper-connection read's gate (fused_gr.cu), so a write done here is bitwise the one it would have folded +__device__ __forceinline__ float sigmoidf_(float x) { return 1.0f / (1.0f + __expf(-x)); } + +// one block per (stream, token): the pending write, then h . v over the stream, then the update +__global__ void cvec_kernel(float* __restrict__ R, const float* __restrict__ dir, const float* __restrict__ s_l, + const int* __restrict__ on, int mode, int64_t layer, int n, int hc, int64_t r_ld, + const float* __restrict__ bo, int64_t bo_ld, const float* __restrict__ inj, + int64_t inj_ld, int write) { + const int c = blockIdx.x; + const int64_t t = blockIdx.y; + float* r = R + t * r_ld + (int64_t) c * n; + const float s = s_l[layer]; + const bool steer = *on != 0 && s != 0.0f; // uniform over the block + if (!steer && !write) return; + const float* v = dir + layer * n; + const float w = write ? 2.0f * sigmoidf_(inj[t * inj_ld + c] / (float) hc) : 0.0f; + const float* b = write ? bo + t * bo_ld : nullptr; + float x[MAXK]; + float dot = 0.0f; +#pragma unroll + for (int k = 0; k < MAXK; ++k) { + const int d = threadIdx.x + k * THREADS; + if (d < n) { + float xv = r[d]; + if (write) xv = fmaf(b[d], w, xv); + x[k] = xv; + if (steer && mode == 0) dot = fmaf(xv, v[d], dot); + } + } + if (steer && mode == 0) { + __shared__ float part[THREADS / 32]; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) dot += __shfl_xor_sync(0xffffffffu, dot, o); + if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = dot; + __syncthreads(); + if (threadIdx.x < 32) { + float p = threadIdx.x < THREADS / 32 ? part[threadIdx.x] : 0.0f; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) p += __shfl_xor_sync(0xffffffffu, p, o); + if (threadIdx.x == 0) part[0] = p; + } + __syncthreads(); + dot = part[0] * s; // s (h . v) + } +#pragma unroll + for (int k = 0; k < MAXK; ++k) { + const int d = threadIdx.x + k * THREADS; + if (d < n) { + float xv = x[k]; + if (steer) xv = mode == 0 ? fmaf(-dot, v[d], xv) : xv + v[d]; + r[d] = xv; + } + } +} + +} // namespace + +const Cvec& cvec() { return g_cvec; } + +bool cvec_upload(const std::vector& dir, const std::vector& s, int mode, int first, int last, + int64_t n_embd, int64_t hc, std::string& err) { + if (n_embd < 1 || n_embd > (int64_t) THREADS * MAXK) { err = "control vector: unsupported n_embd"; return false; } + if (s.empty() || dir.size() != s.size() * (size_t) n_embd) { err = "control vector: bad table sizes"; return false; } + float* d_dir = nullptr; + float* d_s = nullptr; + int* d_on = nullptr; + const int one = 1; + if (cudaMalloc(&d_dir, dir.size() * sizeof(float)) != cudaSuccess || + cudaMalloc(&d_s, s.size() * sizeof(float)) != cudaSuccess || cudaMalloc(&d_on, sizeof(int)) != cudaSuccess || + cudaMemcpy(d_dir, dir.data(), dir.size() * sizeof(float), cudaMemcpyHostToDevice) != cudaSuccess || + cudaMemcpy(d_s, s.data(), s.size() * sizeof(float), cudaMemcpyHostToDevice) != cudaSuccess || + cudaMemcpy(d_on, &one, sizeof(int), cudaMemcpyHostToDevice) != cudaSuccess) { + err = "control vector: device allocation failed"; + return false; + } + g_cvec.dir = d_dir; + g_cvec.s = d_s; + g_cvec.on = d_on; + g_cvec.mode = mode; + g_cvec.first = first; + g_cvec.last = last; + g_cvec.n_embd = n_embd; + g_cvec.hc = hc; + g_cvec.steered.assign(s.size(), false); + for (size_t l = 0; l < s.size(); ++l) g_cvec.steered[l] = s[l] != 0.0f; + g_on = d_on; + g_on_host = true; + return true; +} + +void cvec_set_enabled(bool on) { + if (g_on == nullptr || on == g_on_host) return; + cudaDeviceSynchronize(); // nothing in flight may still read the flag + const int v = on ? 1 : 0; + cudaMemcpy(g_on, &v, sizeof(int), cudaMemcpyHostToDevice); + g_on_host = on; +} + +bool cvec_enabled() { return g_on != nullptr && g_on_host; } + +void cvec_apply(float* R, int64_t layer, int64_t T, int64_t r_ld, const float* bo, int64_t bo_ld, const float* inj, + int64_t inj_ld, bool write, void* stream) { + if (!g_cvec.loaded() || T < 1) return; + const dim3 grid((unsigned) g_cvec.hc, (unsigned) T); + cvec_kernel<<>>(R, g_cvec.dir, g_cvec.s, g_cvec.on, g_cvec.mode, layer, + (int) g_cvec.n_embd, (int) g_cvec.hc, r_ld, bo, bo_ld, + inj, inj_ld, write ? 1 : 0); + if (cudaPeekAtLastError() != cudaSuccess) throw std::runtime_error("cvec_apply: launch failed"); +} + +} // namespace strata::kernels diff --git a/src/kernels/cvec_parity.cpp b/src/kernels/cvec_parity.cpp new file mode 100644 index 00000000..6176c634 --- /dev/null +++ b/src/kernels/cvec_parity.cpp @@ -0,0 +1,223 @@ +// src/kernels/cvec_parity.cpp - the control vector kernel (strata/kernels/cvec.hpp) against a host reference. +// 1. project: h - s (h.v) v per stream and token, against double precision; the steered component is gone. +// 2. add: h + d. +// 3. switched off: R unchanged without a pending write; with one, R is BITWISE the write the fused read folds +// (fused_gr_read with apply), which is what keeps a loaded-but-off vector identical to the stock engine. +// 4. a layer without a direction is untouched. + +#include "strata/kernels/cvec.hpp" +#include "strata/kernels/fused_gr.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; + +namespace { + +int g_fail = 0; + +void ck(cudaError_t e, const char* w) { + if (e != cudaSuccess) { + std::fprintf(stderr, "CUDA error in %s: %s\n", w, cudaGetErrorString(e)); + std::exit(2); + } +} + +template +T* dalloc(size_t n) { + T* p = nullptr; + ck(cudaMalloc(&p, n * sizeof(T)), "malloc"); + return p; +} + +template +void up(T* d, const std::vector& h) { ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "up"); } +template +std::vector down(const T* d, size_t n) { + std::vector h(n); + ck(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost), "down"); + return h; +} + +void check(bool ok, const char* what) { + std::printf(" %-66s %s\n", what, ok ? "ok" : "FAIL"); + if (!ok) ++g_fail; +} + +} // namespace + +int main() { + constexpr int64_t L = 48, N = 2560, HC = 4, LR = 320, T = 5, D = HC * N; + constexpr int64_t kLayer = 7, kOff = 3; // steered / not steered + std::mt19937 rng(1234); + std::normal_distribution nd(0.0f, 1.0f); + + // a unit direction at kLayer with a norm-2 scaled one's s = 2; nothing at kOff + std::vector dir((size_t) (L * N), 0.0f), s((size_t) L, 0.0f); + { + double nrm = 0.0; + std::vector v((size_t) N); + for (auto& x : v) { x = nd(rng); nrm += (double) x * x; } + nrm = std::sqrt(nrm); + for (int64_t j = 0; j < N; ++j) dir[(size_t) (kLayer * N + j)] = (float) (v[(size_t) j] / nrm); + s[(size_t) kLayer] = 2.0f; + } + std::string err; + if (!k::cvec_upload(dir, s, /*project*/ 0, 4, 44, N, HC, err)) { std::fprintf(stderr, "%s\n", err.c_str()); return 2; } + check(k::cvec().covers(kLayer) && !k::cvec().covers(kOff) && !k::cvec().covers(45), "covers(): steered layers only"); + + std::vector R((size_t) (T * D)), bo((size_t) (T * N)), inj((size_t) (T * HC)); + for (auto& x : R) x = nd(rng) * 3.0f; + for (auto& x : bo) x = nd(rng); + for (auto& x : inj) x = nd(rng); + float* dR = dalloc(R.size()); + float* dbo = dalloc(bo.size()); + float* dinj = dalloc(inj.size()); + up(dbo, bo); + up(dinj, inj); + + // ---- 1. project, no pending write + std::printf("project\n"); + up(dR, R); + k::cvec_apply(dR, kLayer, T, D, nullptr, 0, nullptr, 0, false, nullptr); + ck(cudaDeviceSynchronize(), "project"); + { + const auto got = down(dR, R.size()); + double worst = 0.0, worst_dot = 0.0; + for (int64_t t = 0; t < T; ++t) + for (int64_t c = 0; c < HC; ++c) { + const float* h = R.data() + t * D + c * N; + const float* v = dir.data() + kLayer * N; + double dot = 0.0; + for (int64_t j = 0; j < N; ++j) dot += (double) h[j] * v[j]; + double after = 0.0; + for (int64_t j = 0; j < N; ++j) { + const double want = h[j] - 2.0 * dot * v[j]; + const double g = got[(size_t) (t * D + c * N + j)]; + worst = std::fmax(worst, std::fabs(g - want)); + after += g * v[j]; + } + // s = 2 reflects the component: h.v -> -h.v + worst_dot = std::fmax(worst_dot, std::fabs(after + dot)); + } + std::printf(" max |err| %.3g, max |h'.v + h.v| %.3g\n", worst, worst_dot); + check(worst < 1e-4, "project matches h - s (h.v) v (s = 2)"); + check(worst_dot < 1e-3, "the component along v is reflected (s = 2)"); + } + // s = 1 removes it + s[(size_t) kLayer] = 1.0f; + if (!k::cvec_upload(dir, s, 0, 4, 44, N, HC, err)) return 2; + up(dR, R); + k::cvec_apply(dR, kLayer, T, D, nullptr, 0, nullptr, 0, false, nullptr); + ck(cudaDeviceSynchronize(), "project s=1"); + { + const auto got = down(dR, R.size()); + double worst = 0.0; + for (int64_t t = 0; t < T; ++t) + for (int64_t c = 0; c < HC; ++c) { + double after = 0.0; + for (int64_t j = 0; j < N; ++j) after += (double) got[(size_t) (t * D + c * N + j)] * dir[(size_t) (kLayer * N + j)]; + worst = std::fmax(worst, std::fabs(after)); + } + std::printf(" max |h'.v| %.3g\n", worst); + check(worst < 1e-3, "s = 1 projects the direction out"); + } + + // ---- 4. a layer without a direction + up(dR, R); + k::cvec_apply(dR, kOff, T, D, nullptr, 0, nullptr, 0, false, nullptr); + ck(cudaDeviceSynchronize(), "off layer"); + check(std::memcmp(down(dR, R.size()).data(), R.data(), R.size() * 4) == 0, "a layer without a direction is untouched"); + + // ---- 3. switched off + std::printf("switched off\n"); + k::cvec_set_enabled(false); + check(!k::cvec_enabled(), "cvec_enabled() follows the switch"); + up(dR, R); + k::cvec_apply(dR, kLayer, T, D, nullptr, 0, nullptr, 0, false, nullptr); + ck(cudaDeviceSynchronize(), "off"); + check(std::memcmp(down(dR, R.size()).data(), R.data(), R.size() * 4) == 0, "off, no pending write: R unchanged"); + { + // the fused read's folded write, one token at a time, against the kernel's write-only pass + std::vector wd((size_t) (LR * D)), wu((size_t) (D * LR)), wi((size_t) (HC * D)); + std::vector wn((size_t) D); + auto bf = [&](float x) { uint32_t u; std::memcpy(&u, &x, 4); return (uint16_t) (u >> 16); }; + for (auto& x : wd) x = bf(nd(rng) * 0.02f); + for (auto& x : wu) x = bf(nd(rng) * 0.02f); + for (auto& x : wi) x = bf(nd(rng) * 0.02f); + for (auto& x : wn) x = 1.0f + 0.1f * nd(rng); + uint16_t* dwd = dalloc(wd.size()); + uint16_t* dwu = dalloc(wu.size()); + uint16_t* dwi = dalloc(wi.size()); + float* dwn = dalloc(wn.size()); + up(dwd, wd); up(dwu, wu); up(dwi, wi); up(dwn, wn); + float* lo = dalloc(LR); + float* rs = dalloc(HC); + float* inj_out = dalloc(HC); + float* mixed = dalloc(N); + float* dF = dalloc(R.size()); + up(dF, R); + for (int64_t t = 0; t < T; ++t) { + k::FusedGrArgs a; + a.R = dF + t * D; a.R_out = dF + t * D; a.apply = true; + a.bo_prev = dbo + t * N; a.inj_prev = dinj + t * HC; + a.w_norm = dwn; a.w_down = dwd; a.w_up = dwu; a.w_inject = dwi; + a.lo = lo; a.rs = rs; a.inject_out = inj_out; a.mixed = mixed; + k::fused_gr_read(a, nullptr); + } + up(dR, R); + k::cvec_apply(dR, kLayer, T, D, dbo, N, dinj, HC, true, nullptr); + ck(cudaDeviceSynchronize(), "write only"); + const auto fused = down(dF, R.size()), mine = down(dR, R.size()); + check(std::memcmp(fused.data(), mine.data(), R.size() * 4) == 0, + "off, pending write: bitwise the fused read's folded write"); + k::cvec_set_enabled(true); + // on, with the write: the write, then the projection (reference from the fused result) + up(dR, R); + k::cvec_apply(dR, kLayer, T, D, dbo, N, dinj, HC, true, nullptr); + ck(cudaDeviceSynchronize(), "write+project"); + const auto both = down(dR, R.size()); + double worst = 0.0; + for (int64_t t = 0; t < T; ++t) + for (int64_t c = 0; c < HC; ++c) { + const float* h = fused.data() + t * D + c * N; + const float* v = dir.data() + kLayer * N; + double dot = 0.0; + for (int64_t j = 0; j < N; ++j) dot += (double) h[j] * v[j]; + for (int64_t j = 0; j < N; ++j) + worst = std::fmax(worst, std::fabs(both[(size_t) (t * D + c * N + j)] - (h[j] - dot * v[j]))); + } + std::printf(" write + project: max |err| %.3g\n", worst); + check(worst < 1e-4, "on, pending write: the write, then the projection"); + } + + // ---- 2. add + std::printf("add\n"); + for (int64_t j = 0; j < N; ++j) dir[(size_t) (kLayer * N + j)] *= 0.1f; // d = 0.1 v, s = 1 + s[(size_t) kLayer] = 1.0f; + if (!k::cvec_upload(dir, s, /*add*/ 1, 4, 44, N, HC, err)) return 2; + up(dR, R); + k::cvec_apply(dR, kLayer, T, D, nullptr, 0, nullptr, 0, false, nullptr); + ck(cudaDeviceSynchronize(), "add"); + { + const auto got = down(dR, R.size()); + bool same = true; + for (int64_t t = 0; t < T; ++t) + for (int64_t c = 0; c < HC; ++c) + for (int64_t j = 0; j < N; ++j) { + const size_t i = (size_t) (t * D + c * N + j); + same = same && got[i] == R[i] + dir[(size_t) (kLayer * N + j)]; + } + check(same, "add is h + d in every stream (bitwise)"); + } + + std::printf(g_fail ? "cvec_parity: %d FAILED\n" : "cvec_parity: all passed\n", g_fail); + return g_fail ? 1 : 0; +} diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 7419dc31..c8931357 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -10,6 +10,7 @@ #include "strata/kernels/cpu/expert_layout.hpp" #include "strata/kernels/qsa.hpp" #include "strata/kernels/kv_stream.hpp" +#include "strata/kernels/cvec.hpp" #include "strata/kernels/kv_q4.hpp" #include "strata/core/layer.hpp" #include "strata/kernels/qsa_decode_attn.hpp" @@ -651,6 +652,8 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e } // ---- the hyper-connection write of this half gr_write(m.R, m.bo, m.inj, HC, T, m.cs); + if (half == 1 && strata::kernels::cvec().covers(l)) // --control-vector-scaled + strata::kernels::cvec_apply(m.R, l, T, D, nullptr, 0, nullptr, 0, false, m.cs); } } stats_.tokens += T; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 95cd0b1d..6ab939c5 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -44,6 +44,11 @@ #include "strata/program/logits_selection.hpp" #include "strata/spec/draft_policy.hpp" #include "strata/spec/suffix_drafter.hpp" +#include "strata/kernels/cvec.hpp" +#ifndef NOMINMAX +#define NOMINMAX // gguf_reader.hpp includes windows.h +#endif +#include "strata/artifact/gguf_reader.hpp" #include @@ -259,6 +264,13 @@ struct Options { int suffix_draft = 3; /// The MTP's own window cap (0 = --spec): with --spec 6 --mtp-max-t 4 the long windows come from suffix matches. int mtp_max_t = 0; + /// A control vector on the residual stream (strata/kernels/cvec.hpp), with llama.cpp's flags: the + /// `experimental-speed-projection` profile passes `--control-vector-scaled FILE:1.0 --control-vector-layer-range + /// 4 44 --cvec-mode project --cvec-dir per-layer`. None by default; --serve switches a loaded one per request. + std::vector> cvec_files; + int cvec_first = -1, cvec_last = -1; ///< llama.cpp's defaults: 1 .. the last layer + int cvec_mode = 1; ///< 0 = project, 1 = add (llama.cpp's default) + int cvec_single = -1; ///< --cvec-dir single:L (project mode): layer L's direction everywhere }; void usage() { @@ -330,6 +342,11 @@ void usage() { " --suffix-draft N prompt lookup: draft from an earlier repeat of the last N+ tokens of context\n" " when it pays (default 3; 0 = MTP only)\n" " --mtp-max-t M cap the MTP's windows at M tokens (0 = --spec; longer ones come from suffixes)\n" + " --control-vector-scaled FILE:SCALE[,...] a control vector GGUF on the residual stream (llama.cpp's\n" + " format; --control-vector FILE = scale 1). --serve: requests switch it (cvec=0|1)\n" + " --control-vector-layer-range A B the layers it follows (inclusive; default 1 .. the last)\n" + " --cvec-mode add|project h += s v (default) or h -= s (h.v) v with v unit\n" + " --cvec-dir per-layer|single:L each layer's own direction (default) or layer L's everywhere (project)\n" " --no-token-graph A/B: two graphs per layer (the host launches each) instead of one per token\n" " --no-fused-gr A/B: the six-kernel hyper-connection read and a separate write (native)\n" " --prefill CHUNK batched prompt processing in chunks of CHUNK tokens (needs --native)\n" @@ -558,6 +575,80 @@ bool checkpoint_restore(const ConvCheckpoint& c, strata::core::SessionState& ss, return cudaDeviceSynchronize() == cudaSuccess; } +// --control-vector-scaled: llama.cpp's `common_control_vector_load` (every file's `direction.` times its scale, +// summed; layer 0 has none) and `llama_adapter_cvec::apply` with the projection-mode patch (project: the unit +// direction and its norm as the scale), into the tables `cvec_upload` takes. `summary` is what INFO reports. +bool load_control_vectors(const Options& o, const strata::core::ModelGeometry& g, std::string& summary, std::string& err) { + const int64_t L = g.n_layers, N = g.n_embd; + std::vector data((size_t) (L * N), 0.0f); + std::vector have((size_t) L, false); + for (const auto& [path, scale] : o.cvec_files) { + try { + strata::GgufFile f(path); + const strata::MetaValue* arch = f.get("general.architecture"); + if (arch == nullptr || arch->s != "controlvector") { + err = path + ": not a control vector GGUF (general.architecture is not 'controlvector')"; + return false; + } + const strata::MetaValue* hint = f.get("controlvector.model_hint"); + if (hint != nullptr && hint->s != "qwen4exp") + std::fprintf(stderr, "strata generate: %s was made for '%s', not qwen4exp\n", path.c_str(), hint->s.c_str()); + int found = 0; + for (const strata::TensorInfo& t : f.tensors()) { + if (t.name.rfind("direction.", 0) != 0) continue; + const long l = std::strtol(t.name.c_str() + 10, nullptr, 10); + if (l < 1 || l >= L) continue; // layer 0 has no vector; past the model is ignored, as in llama.cpp + if (t.type != 0 || t.elements() != (uint64_t) N) { + err = path + ": " + t.name + " must be " + std::to_string((long long) N) + " f32"; + return false; + } + const float* src = reinterpret_cast(f.tensor_data(t)); + for (int64_t j = 0; j < N; ++j) data[(size_t) (l * N + j)] += scale * src[j]; + have[(size_t) l] = true; + ++found; + } + if (found == 0) { err = path + ": no direction. tensors"; return false; } + } catch (const std::exception& e) { + err = e.what(); + return false; + } + } + const int first = o.cvec_first <= 0 ? 1 : o.cvec_first; + const int last = (o.cvec_last <= 0 || o.cvec_last >= L) ? (int) L - 1 : o.cvec_last; + const int single = o.cvec_mode == 0 ? o.cvec_single : -1; + if (single >= 0 && (single >= L || !have[(size_t) single])) { + err = "--cvec-dir single:" + std::to_string(single) + ": the vector has no direction for that layer"; + return false; + } + std::vector dir((size_t) (L * N), 0.0f), s((size_t) L, 0.0f); + int steered = 0; + for (int64_t l = first; l <= last; ++l) { + const int64_t src = single >= 0 ? single : l; + if (!have[(size_t) src]) continue; + const float* d = data.data() + (size_t) (src * N); + if (o.cvec_mode == 0) { + double nrm = 0.0; + for (int64_t j = 0; j < N; ++j) nrm += (double) d[j] * d[j]; + nrm = std::sqrt(nrm); + if (nrm <= 0.0) continue; + s[(size_t) l] = (float) nrm; + for (int64_t j = 0; j < N; ++j) dir[(size_t) (l * N + j)] = (float) (d[j] / nrm); + } else { + s[(size_t) l] = 1.0f; + std::copy(d, d + N, dir.begin() + (size_t) (l * N)); + } + ++steered; + } + if (steered == 0) { err = "the control vector has no direction in layers " + std::to_string(first) + ".." + std::to_string(last); return false; } + if (!strata::kernels::cvec_upload(dir, s, o.cvec_mode, first, last, N, g.hc, err)) return false; + summary = std::string(o.cvec_mode == 0 ? "project" : "add") + ":" + std::to_string(first) + "-" + std::to_string(last) + + (single >= 0 ? ":single" + std::to_string(single) : ""); + // the line llama.cpp's patched build prints, so a log shows the same thing + std::fprintf(stderr, "strata generate: control vector mode = %s, dir = %s, layers %d..%d (%d steered)\n", + o.cvec_mode == 0 ? "project" : "add", single >= 0 ? "single" : "per-layer", first, last, steered); + return true; +} + } // namespace int main(int argc, char** argv) { @@ -680,6 +771,38 @@ int main(int argc, char** argv) { else if (a == "--short-read") o.short_read = std::max(0LL, std::atoll(next("--short-read"))); else if (a == "--suffix-draft") o.suffix_draft = std::max(0, std::atoi(next("--suffix-draft"))); else if (a == "--mtp-max-t") o.mtp_max_t = std::max(0, std::atoi(next("--mtp-max-t"))); + else if (a == "--control-vector") o.cvec_files.push_back({next("--control-vector"), 1.0f}); + else if (a == "--control-vector-scaled") { + // FILE:SCALE, comma-separated; the LAST colon splits, so a Windows path (C:\...) keeps its drive + std::stringstream list(next("--control-vector-scaled")); + std::string item; + while (std::getline(list, item, ',')) { + const size_t colon = item.rfind(':'); + char* end = nullptr; + const float sc = colon == std::string::npos ? 0.0f : std::strtof(item.c_str() + colon + 1, &end); + if (colon == std::string::npos || colon == 0 || end == item.c_str() + colon + 1 || *end != '\0') { + std::fprintf(stderr, "--control-vector-scaled: expected FILE:SCALE, got '%s'\n", item.c_str()); + return 2; + } + o.cvec_files.push_back({item.substr(0, colon), sc}); + } + } + else if (a == "--control-vector-layer-range") { + o.cvec_first = std::atoi(next("--control-vector-layer-range")); + o.cvec_last = std::atoi(next("--control-vector-layer-range")); + } + else if (a == "--cvec-mode") { + const std::string m = next("--cvec-mode"); + if (m == "project") o.cvec_mode = 0; + else if (m == "add") o.cvec_mode = 1; + else { std::fprintf(stderr, "--cvec-mode: add or project, got '%s'\n", m.c_str()); return 2; } + } + else if (a == "--cvec-dir") { + const std::string d = next("--cvec-dir"); + if (d == "per-layer") o.cvec_single = -1; + else if (d.rfind("single:", 0) == 0) o.cvec_single = std::atoi(d.c_str() + 7); + else { std::fprintf(stderr, "--cvec-dir: per-layer or single:L, got '%s'\n", d.c_str()); return 2; } + } else if (a == "--no-spec-split") o.spec_split = false; else if (a == "--eos-ids") { std::string e; @@ -948,6 +1071,15 @@ int main(int argc, char** argv) { strata::kernels::ple_set_native_postops(o.native_ple_postops); const strata::core::ModelGeometry g; const int64_t K = 10; + // before session_init: every graph captured from here on has the vector's kernels where it applies + std::string cvec_summary = "0"; + if (!o.cvec_files.empty()) { + std::string ce; + if (!load_control_vectors(o, g, cvec_summary, ce)) { + std::fprintf(stderr, "strata generate: control vector: %s\n", ce.c_str()); + return 2; + } + } if (o.max_context < (int64_t) o.tokens.size() + o.max_new) { std::fprintf(stderr, "strata generate: --max-context %lld cannot hold %zu prompt + %lld new tokens\n", (long long) o.max_context, o.tokens.size(), (long long) o.max_new); @@ -2039,6 +2171,7 @@ int main(int argc, char** argv) { std::vector live_imgs, req_imgs; bool live_ok = false; std::vector checks; + bool cvec_cached = true; // the control vector's state the live session and the checkpoints were read with int64_t pp_total = 0, pp_from = 0, pp_next_check = 0; Clock::time_point pp_t0 = Clock::now(); auto imgs_below = [&](const std::vector& all, int64_t L) { @@ -2194,12 +2327,12 @@ int main(int argc, char** argv) { size_t free_b = 0, total_b = 0; cudaMemGetInfo(&free_b, &total_b); std::printf("INFO context=%lld kv=%s kv_resident=%lld expert_slots=%lld expert_cache_mib=%lld spec=%d " - "mtp_max=%d lookup=%d vram_free_mib=%lld\n", + "mtp_max=%d lookup=%d vram_free_mib=%lld cvec=%s\n", (long long) o.max_context, o.kv.c_str(), (long long) (g.n_qsa_layers() > 0 && ss.qsa_states[0].kv_mode == 1 ? ss.qsa_states[0].n_slots * 4 : 0), (long long) xcache.slots(), (long long) (xcache.bytes() >> 20), o.spec, o.mtp_max_t, - o.suffix_draft, (long long) (free_b >> 20)); + o.suffix_draft, (long long) (free_b >> 20), cvec_summary.c_str()); } std::printf("READY %lld stop\n", (long long) o.max_context); // "stop": this engine honours STOP std::fflush(stdout); @@ -2236,7 +2369,8 @@ int main(int argc, char** argv) { unsigned long long req_seed = 0; float req_min_p = 0.0f, req_penalty_repeat = 1.0f, req_penalty_freq = 0.0f, req_penalty_present = 0.0f; int req_penalty_last_n = 0; - if (!geni && endp != nullptr) { + int req_cvec = 1; // cvec=0|1: a loaded control vector for this request (on when absent) + if (endp != nullptr) { // GENI takes only cvec=; its file path is the first token without an = for (;;) { while (*endp == ' ') ++endp; const char* start = endp; @@ -2247,7 +2381,9 @@ int main(int argc, char** argv) { if (eq == std::string::npos) { endp = const_cast(start); break; } const std::string key = tok.substr(0, eq); const float fv = std::strtof(tok.c_str() + eq + 1, nullptr); - if (key == "temperature") req_temperature = fv; + if (key == "cvec") req_cvec = std::atoi(tok.c_str() + eq + 1); + else if (geni) {} // image requests decode greedily + else if (key == "temperature") req_temperature = fv; else if (key == "top_p") req_top_p = fv; else if (key == "top_k") req_top_k = std::atoi(tok.c_str() + eq + 1); else if (key == "min_p") req_min_p = fv; @@ -2373,6 +2509,17 @@ int main(int argc, char** argv) { if ((int32_t) ids[(size_t) i] != pre[(size_t) i]) return false; return imgs_below(req_imgs, L) == pre_imgs; }; + // the control vector for this request. The live session and the checkpoints were read one way, so a + // switch reads the prompt again from the start + if (strata::kernels::cvec().loaded()) { + const bool want = req_cvec != 0; + if (want != cvec_cached) { + live_ok = false; + checks.clear(); + cvec_cached = want; + } + strata::kernels::cvec_set_enabled(want); + } int64_t resume = 0; bool from_live = false; if (o.prompt_cache > 0) {