nx_nofloat_serve_core.nx source
↩ module page · 1244 lines · 58784 B
1// nx_nofloat_serve_core.nx -- the PURE CORE of the no-float LLM serve organ (2026-07-10): model session +
2// greedy generation + HTTP request handler, NO sockets (the daemon shell owns those; the gate exercises this
3// core in-process with synthetic requests -- the proven pure-core+gate+daemon idiom).
4// nsv_init(path) one-time: load GGUF, tokenizer meta, dequant-once i32 (lossless hero) + i8 (fast) caches.
5// nsv_generate(gp) ctx-bundle: sequential CACHED prefill (decode_step per prompt token -- mathematically
6// identical to batch prefill under causal masking) then greedy decode; text out through
7// the byte-level-BPE inverse (nx_nofloat_tokdec) so ' Paris' renders as real text.
8// nsv_handle(...) routes: GET / (app page) GET /health GET /api POST /gen {prompt,max_new,mode}.
9// license_tier: ORIGINAL No hw writes (Rule 26).
10import "nx_syscalls.nx"
11import "nx_tier.nx"
12import "nx_le.nx"
13import "nx_tensor.nx"
14import "nx_gguf.nx"
15import "nx_gguf_load.nx"
16import "nx_gguf_meta.nx"
17import "nx_nofloat_llm.nx"
18import "nx_nofloat_tok.nx"
19import "nx_nofloat_tokdec.nx"
20import "nx_nofloat_arch.nx"
21
22const NSV_MAXT: i64 = 2048 // final prompt+gen TOKEN cap (KV cache rows). L2 raise 384->2048 (FORGE 2026-07-12)
23 // so a mini-pack (~1300 tok) + task + whole-organ generation fits. Decode buffers +
24 // KV cache scale with this: ~+200MB at 2048 for the 0.5B coder (24L, kvd=128, ne=896)
25 // -- well within WSL 16GB alongside the ~700MB model + i32/i8 caches. Gated L2.
26const NSV_MAXIN: i64 = 16384 // max prompt BYTES for the tokenizer's byte-level pretokenize scratch (tok_ptr/tok_len).
27 // L2 raise 8192->16384 for the full mini-pack (3911B) + task headroom.
28 // ⚠ tk_bpe_encode seeds 1 slot per INPUT BYTE -> those buffers MUST be sized by bytes,
29 // NOT NSV_MAXT (the old NSV_MAXT*8 page-rounded to 512 entries -> SIGSEGV on >512-byte prompts).
30const NSV_MAXNEW: i64 = 512 // per-request generation cap (L2 raise 96->512 for whole small organs)
31const NSV_EOS1: i64 = 151643
32const NSV_EOS2: i64 = 151645
33
34static g_nsv_buf: *u8
35static g_nsv_hdr: *NxGgufHeader
36static g_nsv_wc32: *i64
37static g_nsv_wc8: *i64
38static g_nsv_hcp: *i64
39static g_nsv_sb: *i64
40static g_nsv_kvc: *i64
41static g_nsv_freqs: *i64
42static g_nsv_cfgA: *i64
43static g_nsv_cfgF: *i64
44static g_nsv_tmp: *i64
45static g_nsv_x1: *i64
46static g_nsv_h1: *i64
47static g_nsv_normed: *i64
48static g_nsv_gout: *i64
49static g_nsv_idout: *i64
50static g_nsv_lgout: *i64
51static g_nsv_nmbuf: *u8
52static g_nsv_ids: *i64
53static g_nsv_tokp: *i64
54static g_nsv_tokl: *i64
55static g_nsv_lgv: *i64 // full vocab logits (sampling path)
56static g_nsv_mt: *i64 // [0]=mfirst [1]=nm_c [2]=vfirst [3]=vocab [4]=te_base [5]=te_ty [6]=ready [7]=init_ms
57static g_nsv_mpath: *u8 // the ACTUAL loaded model path (health must not lie about which model serves)
58static g_nsv_dims: *i64 // arch-config (nac_read_config 2026-07-15): [0]=D [1]=n_layers [2]=n_heads [3]=n_kv [4]=head_dim [5]=q_dim [6]=kv_dim [7]=ffn [8]=scale_q16 [9]=rope_base [10]=ok
59static g_nsv_kvsnap: *i64 // PREFIX-KV-CACHE (2026-07-15): snapshot of KV rows 0..P-1 (the fixed prompt prefix) for reuse across requests
60static g_nsv_snap_p: i64 // number of prefix tokens currently snapshotted (0 = none)
61static g_nsv_crib_ids: *i64 // the snapshotted prefix's token ids (for common-prefix safety vs BPE re-tokenization)
62
63func nsv_slen(s: *u8) -> i64 { var n: i64=0; while s[n]!=(0 as u8){n=n+1} return n }
64func nsv_cat(dst: *u8, off: i64, s: *u8) -> i64 { var i: i64=0; while s[i]!=(0 as u8){dst[off+i]=s[i];i=i+1} return off+i }
65func nsv_catb(dst: *u8, off: i64, s: *u8, n: i64) -> i64 { var i: i64=0; while i<n {dst[off+i]=s[i];i=i+1} return off+n }
66func nsv_catn(dst: *u8, off: i64, v: i64) -> i64 {
67 var o: i64=off
68 var m: i64=v
69 if m<0 { dst[o]=45 as u8; o=o+1; m=0-m }
70 let t: *u8=sys_mmap(28)
71 var k: i64=0
72 if m==0 { t[0]=48 as u8; k=1 }
73 while m>0 { t[k]=(48+(m%10)) as u8; m=m/10; k=k+1 }
74 var i: i64=0
75 while i<k { dst[o+i]=t[k-1-i]; i=i+1 }
76 return o+k
77}
78
79func nsv_log(s: *u8) -> i64 { var n: i64=0; while s[n]!=(0 as u8){n=n+1} sys_write(1,s,n); return 0 }
80
81// g_nsv_mt layout: [0]=mfirst [1]=nm_c [2]=vfirst [3]=vocab [4]=te_base [5]=te_ty [6]=ready [7]=init_ms
82// [8]=oh_base [9]=oh_ty (head tensor -- passed to nsv_build_caches via statics)
83
84// STAGE 1: read model, parse, resolve tokenizer meta + the 3 tensors, load output-norm. NO pooled calls.
85// Split from nsv_init (single responsibility + lean frame: the fused 150-line init hit an nx_cc large-frame
86// codegen edge -- a GP fault at the first pooled call -- that vanishes when each stage is its own function).
87func nsv_load_meta(path: *u8) -> i64 {
88 let len_out: *i64 = sys_mmap(8) as *i64
89 len_out[0]=0
90 nsv_log(" [init] reading model...\n" as *u8)
91 g_nsv_buf = sys_read_file(path, len_out)
92 if (g_nsv_buf as i64) == 0 { return 1 }
93 g_nsv_hdr = sys_mmap(NX_GGUF_HDR_BYTES) as *NxGgufHeader
94 nsv_log(" [init] parsing gguf...\n" as *u8)
95 if nx_gguf_parse(g_nsv_buf, len_out[0], g_nsv_hdr) != NX_GGUF_OK { return 2 }
96 // ARCH-CONFIG (2026-07-15): dims from the model's own metadata (nac_read_config, gate-proven 07-10) --
97 // ANY Qwen2/Llama-schema gguf serves; for the 0.5B these are the SAME numbers, now read instead of assumed.
98 g_nsv_dims = sys_mmap(16*8) as *i64
99 let arch_out: *u8 = sys_mmap(48)
100 if nac_read_config(g_nsv_buf, len_out[0], g_nsv_hdr, g_nsv_dims, arch_out) != 0 { return 8 }
101 if g_nsv_dims[10] != 1 { return 8 }
102 // FAIL-FAST TYPE SCAN (2026-07-15 debt-eaten): every tensor's quant type must be supported BEFORE we
103 // serve. Unknown types used to zero/wrong-decode SILENTLY mid-token; now init refuses (error 10) and
104 // the daemon never comes up on a model we cannot faithfully decode. (⚠hsc is a FRESH local -- the
105 // first cut used `hloc` which is declared LATER in this fn; nx_cc accepts use-before-declare of a
106 // local and reads stack garbage -> SEGV. The LOCAL sibling of the fwd-static-ref gotcha.)
107 let hsc: *NxGgufHeader = g_nsv_hdr
108 let vbts: *i64 = sys_mmap(16) as *i64
109 var tscan: i64 = 0
110 while tscan < hsc.tensor_count {
111 let tsi: *NxGgufTensorInfo = nx_gguf_tensor_at(hsc, tscan)
112 if nf_type_stride(tsi.ggml_type, vbts) != 0 { return 10 }
113 tscan = tscan + 1
114 }
115 let ne: i64 = g_nsv_dims[0]
116 // hloc: local copy of the static header pointer. This organ FOUND the static-base member-access
117 // miscompile (g_nsv_hdr.data_off returned the pointer, not the field) -- ROOT-FIXED + BLESSED
118 // 2026-07-10 (nx_parse VK_GLOBAL unwrap, nx_static_field_probe pins it). The local copy stays as
119 // style: one load, then cheap field reads.
120 let hloc: *NxGgufHeader = g_nsv_hdr
121 g_nsv_mt = sys_mmap(16*8) as *i64
122 let voff: *i64=sys_mmap(8) as *i64
123 let vty: *i64=sys_mmap(8) as *i64
124 let km: *u8="tokenizer.ggml.merges" as *u8
125 let kt: *u8="tokenizer.ggml.tokens" as *u8
126 if nx_gguf_meta_find(g_nsv_buf, len_out[0], g_nsv_hdr, km, nsv_slen(km), voff, vty)==NX_GMETA_OK {
127 g_nsv_mt[1]=nx_gguf_meta_array_count(g_nsv_buf, voff[0])
128 g_nsv_mt[0]=nx_gguf_meta_array_first_elt_off(g_nsv_buf, voff[0])
129 } else { return 3 }
130 if nx_gguf_meta_find(g_nsv_buf, len_out[0], g_nsv_hdr, kt, nsv_slen(kt), voff, vty)==NX_GMETA_OK {
131 g_nsv_mt[3]=nx_gguf_meta_array_count(g_nsv_buf, voff[0])
132 g_nsv_mt[2]=nx_gguf_meta_array_first_elt_off(g_nsv_buf, voff[0])
133 } else { return 4 }
134 let nt: *u8="token_embd.weight" as *u8
135 let no: *u8="output.weight" as *u8
136 let nn: *u8="output_norm.weight" as *u8
137 let ie: nx_int=nx_gguf_find_tensor(g_nsv_hdr, nt, 17)
138 var io: nx_int=nx_gguf_find_tensor(g_nsv_hdr, no, 13)
139 let inn: nx_int=nx_gguf_find_tensor(g_nsv_hdr, nn, 18)
140 if ie<0 { return 5 }
141 if io<0 { io = ie } // tied-embeddings fallback: qwen2-0.5b ties lm_head to token_embd; embedding-model GGUFs (jina) omit output.weight entirely
142 if inn<0 { return 5 }
143 let te: *NxGgufTensorInfo=nx_gguf_tensor_at(hloc, ie)
144 g_nsv_mt[4]=hloc.data_off+te.offset
145 g_nsv_mt[5]=te.ggml_type
146 let oh: *NxGgufTensorInfo=nx_gguf_tensor_at(hloc, io)
147 g_nsv_mt[8]=hloc.data_off+oh.offset
148 g_nsv_mt[9]=oh.ggml_type
149 nsv_log(" [init] tensors located; loading output norm...\n" as *u8)
150 g_nsv_gout=sys_mmap(ne*8) as *i64
151 load_named_q16(g_nsv_buf, g_nsv_hdr, nn, 18, g_nsv_gout, ne)
152 return 0
153}
154
155// STAGE 2: allocate all per-request scratch + KV caches (sized to the serve MAXT). NO pooled calls.
156func nsv_alloc_scratch() -> i64 {
157 let ne: i64 = g_nsv_dims[0]
158 let qd: i64 = g_nsv_dims[5]
159 let kvd: i64 = g_nsv_dims[6]
160 let fd: i64 = g_nsv_dims[7]
161 let nl: i64 = g_nsv_dims[1]
162 let hd: i64 = g_nsv_dims[4]
163 nsv_log(" [init] allocating scratch + kv...\n" as *u8)
164 g_nsv_sb=sys_mmap(14*8) as *i64
165 g_nsv_sb[0]=sys_mmap(NSV_MAXT*ne*8) as i64
166 g_nsv_sb[1]=sys_mmap(NSV_MAXT*qd*8) as i64
167 g_nsv_sb[2]=sys_mmap(NSV_MAXT*kvd*8) as i64
168 g_nsv_sb[3]=sys_mmap(NSV_MAXT*kvd*8) as i64
169 g_nsv_sb[4]=sys_mmap(NSV_MAXT*qd*8) as i64
170 g_nsv_sb[5]=sys_mmap(NSV_MAXT*8) as i64
171 g_nsv_sb[6]=sys_mmap(NSV_MAXT*8) as i64
172 g_nsv_sb[7]=sys_mmap(NSV_MAXT*ne*8) as i64
173 g_nsv_sb[8]=sys_mmap(NSV_MAXT*fd*8) as i64
174 g_nsv_sb[9]=sys_mmap(NSV_MAXT*fd*8) as i64
175 g_nsv_sb[10]=sys_mmap(NSV_MAXT*fd*8) as i64
176 g_nsv_sb[11]=sys_mmap(NSV_MAXT*ne*8) as i64
177 g_nsv_sb[12]=sys_mmap(NSV_MAXT*ne*8) as i64
178 g_nsv_sb[13]=sys_mmap(NSV_MAXT*ne*8) as i64
179 g_nsv_kvc=sys_mmap(2*nl*8) as *i64
180 var kl: i64=0
181 while kl<nl { g_nsv_kvc[2*kl]=sys_mmap(NSV_MAXT*kvd*8) as i64; g_nsv_kvc[2*kl+1]=sys_mmap(NSV_MAXT*kvd*8) as i64; kl=kl+1 }
182 g_nsv_nmbuf=sys_mmap(64)
183 g_nsv_freqs=sys_mmap(hd*8) as *i64
184 rope_freqs(g_nsv_freqs, hd)
185 g_nsv_tmp=sys_mmap(64*256*8) as *i64
186 g_nsv_x1=sys_mmap(ne*8) as *i64
187 g_nsv_h1=sys_mmap(ne*8) as *i64
188 g_nsv_normed=sys_mmap(ne*8) as *i64
189 g_nsv_idout=sys_mmap(8) as *i64
190 g_nsv_lgout=sys_mmap(8) as *i64
191 g_nsv_ids=sys_mmap(NSV_MAXT*8) as *i64
192 g_nsv_tokp=sys_mmap(NSV_MAXIN*8) as *i64 // 1 slot per INPUT BYTE (byte-level pretokenize) -> size by BYTES
193 g_nsv_tokl=sys_mmap(NSV_MAXIN*8) as *i64
194 let vcl: i64 = g_nsv_mt[3]
195 g_nsv_lgv=sys_mmap(vcl*8) as *i64
196 g_nsv_cfgA=sys_mmap(8*8) as *i64
197 g_nsv_cfgA[1]=ne
198 g_nsv_cfgA[2]=g_nsv_dims[2]
199 g_nsv_cfgA[3]=g_nsv_dims[3]
200 g_nsv_cfgA[4]=hd
201 g_nsv_cfgA[5]=qd
202 g_nsv_cfgA[6]=kvd
203 g_nsv_cfgA[7]=g_nsv_dims[8]
204 g_nsv_cfgF=sys_mmap(4*8) as *i64
205 g_nsv_cfgF[1]=ne
206 g_nsv_cfgF[2]=fd
207 return 0
208}
209
210// ---- one-time session init (fail-fast: any error -> nonzero, organ must not serve). Thin orchestrator
211// over three lean stages -- each its own frame so the pooled STAGE 3 never shares a frame with the big
212// STAGE 1/2 setup (the large-frame codegen edge that GP-faulted the fused version). ----
213// LIGHT INIT (2026-07-16, memory-proportionate loading): i8-only serve skips the i32 weight cache (~4 bytes/param
214// -- the single biggest allocation; ~6GB at 1.5B) so a mode-1-pinned organ fits comfortably inside the WSL VM
215// (host-pressure kills root-caused: 32GB host, dual-cache 1.5B init ~11GB -> intermittent SIGKILL of the tree).
216// Head cache stays (sampling needs full logits). CONTRACT: after nsv_init_i8, callers MUST pin mode=1 (gp[3]=1);
217// mode 0 would read the absent i32 cache.
218static g_nsv_i8only: i64
219func nsv_init_i8(path: *u8) -> i64 {
220 g_nsv_i8only = 1
221 return nsv_init(path)
222}
223func nsv_init(path: *u8) -> i64 {
224 let t0: i64 = sys_now_ms()
225 g_nsv_mpath = path
226 // Spawn the worker pool at startup (fail-fast: workers ready before the first request, not on first
227 // token). nf_pool is idempotent -> the cache build + every decode reuse this instance.
228 nsv_log(" [init] pre-warming worker pool...\n" as *u8)
229 nf_pool()
230 let rc1: i64 = nsv_load_meta(path)
231 if rc1 != 0 { return rc1 }
232 nsv_alloc_scratch()
233 let brc: i64 = nsv_build_caches()
234 if brc != 0 { return brc }
235 g_nsv_mt[7]=sys_now_ms()-t0
236 g_nsv_mt[6]=1
237 return 0
238}
239
240// STAGE 3: build the dequant-once caches (i32 head + i32 layers + i8 layers). The ONLY pooled stage;
241// reads oh_base/oh_ty from g_nsv_mt[8]/[9]. Lean frame = no GP fault at nf_pool() first-touch.
242func nsv_build_caches() -> i64 {
243 let ne: i64 = g_nsv_dims[0]
244 let qd: i64 = g_nsv_dims[5]
245 let kvd: i64 = g_nsv_dims[6]
246 let fd: i64 = g_nsv_dims[7]
247 let nl: i64 = g_nsv_dims[1]
248 let oh_base: i64 = g_nsv_mt[8]
249 let oh_ty: i64 = g_nsv_mt[9]
250 let vcb: i64 = g_nsv_mt[3]
251 nsv_log(" [init] building i32 head cache...\n" as *u8)
252 let hcache: *i32 = nf_dequant_head_all_i32(g_nsv_buf, oh_base, oh_ty, vcb, ne)
253 if (hcache as i64) <= 0 { return 7 }
254 if g_nsv_i8only == 0 {
255 nsv_log(" [init] building i32 weight cache (dequant-once)...\n" as *u8)
256 g_nsv_wc32=sys_mmap(nl*8) as *i64
257 let ovf: i64=nf_dequant_all_layers_i32(g_nsv_buf, g_nsv_hdr, g_nsv_wc32, nl, ne, qd, kvd, fd)
258 if ovf != 0 { return 6 }
259 } else {
260 nsv_log(" [init] i8-only: skipping i32 weight cache (memory-proportionate)\n" as *u8)
261 }
262 nsv_log(" [init] building i8 weight cache...\n" as *u8)
263 g_nsv_wc8=sys_mmap(nl*8) as *i64
264 nf_dequant_all_layers_i8(g_nsv_buf, g_nsv_hdr, g_nsv_wc8, nl, ne, qd, kvd, fd)
265 nsv_log(" [init] caches ready\n" as *u8)
266 g_nsv_hcp=sys_mmap(6*8) as *i64
267 g_nsv_hcp[0]=hcache as i64
268 g_nsv_hcp[1]=g_nsv_normed as i64
269 g_nsv_hcp[2]=g_nsv_mt[3]
270 g_nsv_hcp[3]=ne
271 g_nsv_hcp[4]=g_nsv_idout as i64
272 g_nsv_hcp[5]=g_nsv_lgout as i64
273 return 0
274}
275
276// one cached decode step at pos in the requested mode (0=i32 lossless, 1=i8 SIMD fast).
277func nsv_step(pos: i64, mode: i64) -> i64 {
278 if mode == 1 {
279 decode_step_kv_cached_i8(g_nsv_buf, g_nsv_hdr, g_nsv_x1, g_nsv_h1, g_nsv_wc8, g_nsv_sb, g_nsv_nmbuf, g_nsv_freqs, g_nsv_kvc, pos, g_nsv_cfgA, g_nsv_cfgF, g_nsv_dims[1])
280 } else {
281 decode_step_kv_cached_i32(g_nsv_buf, g_nsv_hdr, g_nsv_x1, g_nsv_h1, g_nsv_wc32, g_nsv_sb, g_nsv_nmbuf, g_nsv_freqs, g_nsv_kvc, pos, g_nsv_cfgA, g_nsv_cfgF, g_nsv_dims[1])
282 }
283 return 0
284}
285
286// xorshift64* PRNG step; state at sp[0] (never 0). Deterministic per seed -- "same in -> same bytes" holds
287// with the seed as part of the in.
288func nsv_rand(sp: *i64) -> i64 {
289 var s: i64 = sp[0]
290 s = s ^ (s >> 12)
291 s = s ^ (s << 25)
292 s = s ^ (s >> 27)
293 sp[0] = s
294 var r: i64 = s * 2685821657736338717
295 if r < 0 { r = 0 - r }
296 if r < 0 { r = 0 }
297 return r
298}
299// temperature/top-k/top-p sampling over the full logit vector -- 100 percent integer (logits are Q16 head
300// convention; fx_exp is the same Q16 exp the attention softmax rides). sp = [lgv, vocab, temp_pm, top_p_pm,
301// top_k, seed_state_ptr]. Returns the sampled token id.
302func nsv_sample(sp: *i64) -> i64 {
303 let lgv: *i64 = sp[0] as *i64
304 let vocab: i64 = sp[1]
305 var temp_pm: i64 = sp[2]
306 var top_p_pm: i64 = sp[3]
307 var k: i64 = sp[4]
308 let sd: *i64 = sp[5] as *i64
309 if temp_pm < 1 { temp_pm = 1 }
310 if temp_pm > 5000 { temp_pm = 5000 }
311 if top_p_pm < 1 { top_p_pm = 1 }
312 if top_p_pm > 1000 { top_p_pm = 1000 }
313 if k < 1 { k = 1 }
314 if k > 256 { k = 256 }
315 // top-k select (insertion into a small descending array; common case = 1 compare reject)
316 let kid: *i64 = sys_mmap(256*8) as *i64
317 let klg: *i64 = sys_mmap(256*8) as *i64
318 var n: i64 = 0
319 var v: i64 = 0
320 while v < vocab {
321 let l: i64 = lgv[v]
322 var take: i64 = 0
323 if n < k { take = 1 } else { if l > klg[n-1] { take = 1 } }
324 if take == 1 {
325 var pos: i64 = n
326 if pos >= k { pos = k - 1 }
327 var j: i64 = pos
328 while j > 0 { if l > klg[j-1] { klg[j]=klg[j-1]; kid[j]=kid[j-1]; j=j-1 } else { j = 0 - j } }
329 if j < 0 { j = 0 - j }
330 klg[j]=l
331 kid[j]=v
332 if n < k { n = n + 1 }
333 }
334 v = v + 1
335 }
336 // temperature -> Q16 exp weights (max-subtracted so fx_exp sees <= 0)
337 let ev: *i64 = sys_mmap(256*8) as *i64
338 let base: i64 = klg[0]
339 var total: i64 = 0
340 var i: i64 = 0
341 while i < n {
342 let x: i64 = ((klg[i] - base) * 1000) / temp_pm
343 let e: i64 = fx_exp(x)
344 ev[i] = e
345 total = total + e
346 i = i + 1
347 }
348 if total <= 0 { return kid[0] }
349 // top-p nucleus: keep the smallest prefix (descending) whose mass >= top_p_pm/1000 of total
350 let cutoff: i64 = (top_p_pm * total) / 1000
351 var m: i64 = 0
352 var cum: i64 = 0
353 var going: i64 = 1
354 while going == 1 {
355 if m >= n { going = 0 } else {
356 cum = cum + ev[m]
357 m = m + 1
358 if cum >= cutoff { going = 0 }
359 }
360 }
361 if m < 1 { m = 1 }
362 var mtotal: i64 = 0
363 i = 0
364 while i < m { mtotal = mtotal + ev[i]; i = i + 1 }
365 if mtotal <= 0 { return kid[0] }
366 // draw
367 let r: i64 = nsv_rand(sd) % mtotal
368 var c2: i64 = 0
369 i = 0
370 while i < m { c2 = c2 + ev[i]; if c2 > r { return kid[i] } i = i + 1 }
371 return kid[m-1]
372}
373// pick the next token from the current normed hidden state. np = [temp_pm, top_p_pm, top_k, seed_state_ptr].
374// temp_pm==0 -> greedy argmax (the bit-exact hero path, unchanged); else full-logits head + seeded sampling.
375func nsv_next_token(np: *i64) -> i64 {
376 if np[0] == 0 { return head_argmax_cached_i32(g_nsv_hcp) }
377 let hlp: *i64 = sys_mmap(6*8) as *i64
378 hlp[0]=g_nsv_hcp[0]
379 hlp[1]=g_nsv_normed as i64
380 hlp[2]=g_nsv_mt[3]
381 hlp[3]=g_nsv_cfgA[1]
382 hlp[4]=g_nsv_lgv as i64
383 head_logits_cached_i32(hlp)
384 let sp: *i64 = sys_mmap(6*8) as *i64
385 sp[0]=g_nsv_lgv as i64
386 sp[1]=g_nsv_mt[3]
387 sp[2]=np[0]
388 sp[3]=np[1]
389 sp[4]=np[2]
390 sp[5]=np[3]
391 return nsv_sample(sp)
392}
393// decode token `tok` to text: append to the out buffer AND (if ep[3]=fd >= 0) emit one SSE frame
394// `data: {"piece":"..."}` to the stream. ep = [out, olen, ocap, fd]. Returns the new olen.
395func nsv_emit_piece(tok: i64, ep: *i64) -> i64 {
396 let out: *u8 = ep[0] as *u8
397 var olen: i64 = ep[1]
398 let ocap: i64 = ep[2]
399 let fd: i64 = ep[3]
400 let off: i64 = tk_decode_off(g_nsv_buf, g_nsv_mt[2], tok)
401 let pl: i64 = nx_gguf_meta_read_string_len(g_nsv_buf, off)
402 if pl < 1 { return olen }
403 let tmp: *u8 = sys_mmap(1024)
404 let tn: i64 = td_piece_decode(nx_gguf_meta_read_string_ptr(g_nsv_buf, off), pl, tmp, 0, 1000)
405 var i: i64 = 0
406 while i < tn { if olen < ocap { out[olen]=tmp[i]; olen=olen+1 } i = i + 1 }
407 if fd >= 0 {
408 let fr: *u8 = sys_mmap(4096)
409 var fo: i64 = nsv_cat(fr, 0, "data: {\"piece\":\"" as *u8)
410 fo = nsv_jesc(fr, fo, tmp, tn)
411 fo = nsv_cat(fr, fo, "\"}\n\n" as *u8)
412 var w: i64 = 0
413 while w < fo { let kw: i64 = sys_write(fd, ((fr as i64)+w) as *u8, fo-w); if kw <= 0 { w = fo } else { w = w + kw } }
414 }
415 return olen
416}
417
418// build a ChatML prompt id sequence into g_nsv_ids:
419// <|im_start|>user\n{content}<|im_end|>\n<|im_start|>assistant\n
420// special ids 151644 (im_start) / 151645 (im_end == NSV_EOS2) are SPLICED directly (tk_bpe_encode
421// is pure byte-BPE and would byte-encode the marker text). Everything INLINE -- no multi-data-arg
422// helper (the documented 3+-arg miscompile class). Returns nprompt (total ids). Lets the INSTRUCT
423// model see turn structure. tmpids: tk_bpe_encode writes from index 0, so encode into it then copy.
424func nsv_chatml_ids(content: *u8, clen: i64) -> i64 {
425 let base: i64 = g_nsv_ids as i64
426 var off: i64 = 0
427 // <|im_start|>
428 g_nsv_ids[off] = 151644
429 off = off + 1
430 // user\n (encode IN-PLACE into g_nsv_ids[off..] -- the proven single-call buffer)
431 let po1: i64 = base + off*8
432 let ip1: *i64 = po1 as *i64
433 let nu: i64 = tk_bpe_encode(g_nsv_buf, g_nsv_mt[0], g_nsv_mt[1], g_nsv_mt[2], g_nsv_mt[3], "user\n" as *u8, 5, g_nsv_tokp, g_nsv_tokl, ip1)
434 off = off + nu
435 // content
436 let po2: i64 = base + off*8
437 let ip2: *i64 = po2 as *i64
438 let nc: i64 = tk_bpe_encode(g_nsv_buf, g_nsv_mt[0], g_nsv_mt[1], g_nsv_mt[2], g_nsv_mt[3], content, clen, g_nsv_tokp, g_nsv_tokl, ip2)
439 off = off + nc
440 // <|im_end|>
441 g_nsv_ids[off] = 151645
442 off = off + 1
443 // \n
444 let po3: i64 = base + off*8
445 let ip3: *i64 = po3 as *i64
446 let nn: i64 = tk_bpe_encode(g_nsv_buf, g_nsv_mt[0], g_nsv_mt[1], g_nsv_mt[2], g_nsv_mt[3], "\n" as *u8, 1, g_nsv_tokp, g_nsv_tokl, ip3)
447 off = off + nn
448 // <|im_start|>
449 g_nsv_ids[off] = 151644
450 off = off + 1
451 // assistant\n
452 let po4: i64 = base + off*8
453 let ip4: *i64 = po4 as *i64
454 let na: i64 = tk_bpe_encode(g_nsv_buf, g_nsv_mt[0], g_nsv_mt[1], g_nsv_mt[2], g_nsv_mt[3], "assistant\n" as *u8, 10, g_nsv_tokp, g_nsv_tokl, ip4)
455 off = off + na
456 return off
457}
458
459// generation. gp = [prompt, plen, max_new, mode, out_text, otcap, meta, stream_fd(-1=none),
460// temp_pm(0=greedy), top_p_pm, top_k, seed, chatml(1=wrap prompt in ChatML)].
461// meta out: [0]=n_prompt [1]=n_gen [2]=ms_total [3]=ms_per_tok [4]=eos [5]=err. returns text length (-1 on err).
462func nsv_generate(gp: *i64) -> i64 {
463 let prompt: *u8 = gp[0] as *u8
464 let plen: i64 = gp[1]
465 var max_new: i64 = gp[2]
466 let mode: i64 = gp[3]
467 let out: *u8 = gp[4] as *u8
468 let ocap: i64 = gp[5]
469 let meta: *i64 = gp[6] as *i64
470 meta[0]=0
471 meta[1]=0
472 meta[2]=0
473 meta[3]=0
474 meta[4]=0
475 meta[5]=0
476 if g_nsv_mt[6] != 1 { meta[5]=9; return 0-1 }
477 if plen < 1 { meta[5]=1; return 0-1 }
478 if max_new < 1 { max_new = 24 }
479 if max_new > NSV_MAXNEW { max_new = NSV_MAXNEW }
480 var nprompt: i64 = 0
481 if gp[12] == 1 { nprompt = nsv_chatml_ids(prompt, plen) }
482 else { nprompt = tk_bpe_encode(g_nsv_buf, g_nsv_mt[0], g_nsv_mt[1], g_nsv_mt[2], g_nsv_mt[3], prompt, plen, g_nsv_tokp, g_nsv_tokl, g_nsv_ids) }
483 if nprompt < 1 { meta[5]=2; return 0-1 }
484 if nprompt >= NSV_MAXT - 2 { meta[5]=3; return 0-1 }
485 if nprompt + max_new >= NSV_MAXT { max_new = NSV_MAXT - 1 - nprompt }
486 meta[0]=nprompt
487 let ne: i64 = g_nsv_cfgA[1]
488 // sampling params (gp[8]=temp_pm 0=greedy, gp[9]=top_p_pm, gp[10]=top_k, gp[11]=seed) + stream fd (gp[7])
489 let np: *i64 = sys_mmap(4*8) as *i64
490 let sd: *i64 = sys_mmap(8) as *i64
491 var seed: i64 = gp[11]
492 if seed == 0 { seed = 88172645463325252 }
493 sd[0]=seed
494 np[0]=gp[8]
495 np[1]=gp[9]
496 np[2]=gp[10]
497 np[3]=sd as i64
498 let ep: *i64 = sys_mmap(4*8) as *i64
499 ep[0]=out as i64
500 ep[1]=0
501 ep[2]=ocap
502 ep[3]=gp[7]
503 let t0: i64 = sys_now_ms()
504 // sequential CACHED prefill: run each prompt token through the single-token cached step. Causal masking
505 // makes this bit-identical to batch prefill (row t only ever attends 0..t) -- and it rides the dequant-once
506 // caches, so there is NO per-request re-dequant of the model.
507 var i: i64 = 0
508 while i < nprompt {
509 dequant_row(g_nsv_buf, g_nsv_mt[4], g_nsv_mt[5], g_nsv_ids[i], ne, g_nsv_x1, g_nsv_tmp)
510 nsv_step(i, mode)
511 i = i + 1
512 }
513 rmsnorm_gamma_row_q24(g_nsv_h1, g_nsv_gout, 0, ne, g_nsv_normed, 0)
514 var next: i64 = nsv_next_token(np)
515 var T: i64 = nprompt
516 g_nsv_ids[T]=next
517 T=T+1
518 var ngen: i64 = 1
519 var stop: i64 = 0
520 if next==NSV_EOS1 { stop=1; meta[4]=1 }
521 if next==NSV_EOS2 { stop=1; meta[4]=1 }
522 if stop == 0 { ep[1] = nsv_emit_piece(next, ep) }
523 while stop == 0 {
524 if ngen >= max_new { stop = 1 } else { if T >= NSV_MAXT { stop = 1 } else {
525 let pos: i64 = T - 1
526 dequant_row(g_nsv_buf, g_nsv_mt[4], g_nsv_mt[5], g_nsv_ids[pos], ne, g_nsv_x1, g_nsv_tmp)
527 nsv_step(pos, mode)
528 rmsnorm_gamma_row_q24(g_nsv_h1, g_nsv_gout, 0, ne, g_nsv_normed, 0)
529 next = nsv_next_token(np)
530 g_nsv_ids[T]=next
531 T=T+1
532 ngen=ngen+1
533 if next==NSV_EOS1 { stop=1; meta[4]=1 }
534 if next==NSV_EOS2 { stop=1; meta[4]=1 }
535 if meta[4] == 0 { ep[1] = nsv_emit_piece(next, ep) }
536 } }
537 }
538 let t1: i64 = sys_now_ms()
539 meta[1]=ngen
540 meta[2]=t1-t0
541 if ngen > 0 { meta[3]=(t1-t0)/(nprompt+ngen) }
542 return ep[1]
543}
544
545// ---- PREFIX-KV-CACHE (2026-07-15): the forge re-prefills a FIXED crib (~130 tok) on every task. Snapshot the
546// crib's KV rows 0..P-1 ONCE, restore them per task -> skip re-prefilling the crib (~P fewer prefill steps/task).
547// BIT-EXACT by causal masking: row t only attends 0..t, so the crib K/V are identical with or without the suffix
548// (the code already relies on this for sequential==batch prefill). Additive: the live nsv_generate is untouched.
549func nsv_kv_snapshot(P: i64) -> i64 {
550 let kvd: i64 = g_nsv_dims[6]
551 let nl: i64 = g_nsv_dims[1]
552 let per: i64 = P * kvd
553 g_nsv_kvsnap = sys_mmap(2 * nl * per * 8) as *i64
554 g_nsv_snap_p = P
555 g_nsv_crib_ids = sys_mmap(P * 8) as *i64
556 var s: i64 = 0
557 while s < P { g_nsv_crib_ids[s] = g_nsv_ids[s]; s = s + 1 }
558 var L: i64 = 0
559 while L < nl {
560 let K: *i64 = g_nsv_kvc[2*L] as *i64
561 let V: *i64 = g_nsv_kvc[2*L+1] as *i64
562 let base: i64 = (2*L) * per
563 var e: i64 = 0
564 while e < per {
565 g_nsv_kvsnap[base + e] = K[e]
566 g_nsv_kvsnap[base + per + e] = V[e]
567 e = e + 1
568 }
569 L = L + 1
570 }
571 return 0
572}
573func nsv_kv_restore() -> i64 {
574 if (g_nsv_kvsnap as i64) == 0 { return 0 - 1 }
575 let kvd: i64 = g_nsv_dims[6]
576 let nl: i64 = g_nsv_dims[1]
577 let P: i64 = g_nsv_snap_p
578 let per: i64 = P * kvd
579 var L: i64 = 0
580 while L < nl {
581 let K: *i64 = g_nsv_kvc[2*L] as *i64
582 let V: *i64 = g_nsv_kvc[2*L+1] as *i64
583 let base: i64 = (2*L) * per
584 var e: i64 = 0
585 while e < per {
586 K[e] = g_nsv_kvsnap[base + e]
587 V[e] = g_nsv_kvsnap[base + per + e]
588 e = e + 1
589 }
590 L = L + 1
591 }
592 return 0
593}
594// DISK-PERSISTED snapshot (2026-07-15): the crib KV survives process restarts -- a fresh process loads the
595// snapshot instead of re-prefilling (the WSL/daemon-restart pattern). Format: [P][nl][kvd] then crib ids
596// (P i64) then per-layer K rows then V rows (P*kvd i64 each). Load fail-safe: any dim mismatch -> -1, caller
597// falls back to full prefill (never a wrong cache).
598func nsv_kv_snapshot_save(path: *u8) -> i64 {
599 if (g_nsv_kvsnap as i64) == 0 { return 0 - 1 }
600 let kvd: i64 = g_nsv_dims[6]
601 let nl: i64 = g_nsv_dims[1]
602 let P: i64 = g_nsv_snap_p
603 let per: i64 = P * kvd
604 let fd: i64 = sys_openat_wr(path, 0x1a4)
605 if fd < 0 { return 0 - 2 }
606 let hdrb: *i64 = sys_mmap(3*8) as *i64
607 hdrb[0] = P
608 hdrb[1] = nl
609 hdrb[2] = kvd
610 sys_write(fd, hdrb as *u8, 24)
611 sys_write(fd, g_nsv_crib_ids as *u8, P*8)
612 sys_write(fd, g_nsv_kvsnap as *u8, 2*nl*per*8)
613 sys_close(fd)
614 return 0
615}
616func nsv_kv_snapshot_load(path: *u8) -> i64 {
617 let kvd: i64 = g_nsv_dims[6]
618 let nl: i64 = g_nsv_dims[1]
619 let fd: i64 = sys_openat_rd(path)
620 if fd < 0 { return 0 - 1 }
621 let hdrb: *i64 = sys_mmap(3*8) as *i64
622 if sys_read(fd, hdrb as *u8, 24) != 24 { sys_close(fd); return 0 - 2 }
623 let P: i64 = hdrb[0]
624 if P < 1 { sys_close(fd); return 0 - 3 }
625 if P >= NSV_MAXT { sys_close(fd); return 0 - 3 }
626 if hdrb[1] != nl { sys_close(fd); return 0 - 4 }
627 if hdrb[2] != kvd { sys_close(fd); return 0 - 4 }
628 let per: i64 = P * kvd
629 g_nsv_crib_ids = sys_mmap(P*8) as *i64
630 g_nsv_kvsnap = sys_mmap(2*nl*per*8) as *i64
631 var need: i64 = P*8
632 var got: i64 = 0
633 var q: *u8 = g_nsv_crib_ids as *u8
634 while got < need { let r: i64 = sys_read(fd, (q as i64 + got) as *u8, need - got); if r <= 0 { sys_close(fd); return 0 - 5 } got = got + r }
635 need = 2*nl*per*8
636 got = 0
637 q = g_nsv_kvsnap as *u8
638 while got < need { let r2: i64 = sys_read(fd, (q as i64 + got) as *u8, need - got); if r2 <= 0 { sys_close(fd); return 0 - 5 } got = got + r2 }
639 sys_close(fd)
640 g_nsv_snap_p = P
641 return P
642}
643
644// nsv_generate with prefix-KV-cache. prefix_len = # prompt tokens shared with the snapshot; use_snap: 0 = prefill
645// all + snapshot rows 0..prefix_len-1; 1 = restore the snapshot + prefill only [prefix_len..nprompt). Requires
646// prefix_len < nprompt when use_snap==1 (a suffix must exist). Everything after prefill is byte-identical to
647// nsv_generate (same decode, sampling, emit) -> the OUTPUT must match nsv_generate exactly (the gate proves it).
648func nsv_generate_pfx(gp: *i64, prefix_len: i64, use_snap: i64) -> i64 {
649 let prompt: *u8 = gp[0] as *u8
650 let plen: i64 = gp[1]
651 var max_new: i64 = gp[2]
652 let mode: i64 = gp[3]
653 let out: *u8 = gp[4] as *u8
654 let ocap: i64 = gp[5]
655 let meta: *i64 = gp[6] as *i64
656 meta[0]=0
657 meta[1]=0
658 meta[2]=0
659 meta[3]=0
660 meta[4]=0
661 meta[5]=0
662 if g_nsv_mt[6] != 1 { meta[5]=9; return 0-1 }
663 if plen < 1 { meta[5]=1; return 0-1 }
664 if max_new < 1 { max_new = 24 }
665 if max_new > NSV_MAXNEW { max_new = NSV_MAXNEW }
666 var nprompt: i64 = 0
667 if gp[12] == 1 { nprompt = nsv_chatml_ids(prompt, plen) }
668 else { nprompt = tk_bpe_encode(g_nsv_buf, g_nsv_mt[0], g_nsv_mt[1], g_nsv_mt[2], g_nsv_mt[3], prompt, plen, g_nsv_tokp, g_nsv_tokl, g_nsv_ids) }
669 if nprompt < 1 { meta[5]=2; return 0-1 }
670 if nprompt >= NSV_MAXT - 2 { meta[5]=3; return 0-1 }
671 if nprompt + max_new >= NSV_MAXT { max_new = NSV_MAXT - 1 - nprompt }
672 meta[0]=nprompt
673 let ne: i64 = g_nsv_cfgA[1]
674 let np: *i64 = sys_mmap(4*8) as *i64
675 let sd: *i64 = sys_mmap(8) as *i64
676 var seed: i64 = gp[11]
677 if seed == 0 { seed = 88172645463325252 }
678 sd[0]=seed
679 np[0]=gp[8]
680 np[1]=gp[9]
681 np[2]=gp[10]
682 np[3]=sd as i64
683 let ep: *i64 = sys_mmap(4*8) as *i64
684 ep[0]=out as i64
685 ep[1]=0
686 ep[2]=ocap
687 ep[3]=gp[7]
688 let t0: i64 = sys_now_ms()
689 // no-snapshot fallback: use_snap=1 with no prior snapshot degrades to a full prefill (never crashes)
690 var us: i64 = use_snap
691 if us == 1 { if (g_nsv_kvsnap as i64) == 0 { us = 0 } }
692 var i: i64 = 0
693 if us == 1 {
694 nsv_kv_restore()
695 // BOUNDARY-SAFE: only the token rows that ACTUALLY match the snapshotted crib are trusted; the first
696 // divergent token (BPE may re-tokenize the crib/task seam) and everything after is re-prefilled fresh.
697 var cp: i64 = 0
698 var go: i64 = 1
699 while go == 1 {
700 if cp >= g_nsv_snap_p { go = 0 }
701 else { if cp >= nprompt { go = 0 }
702 else { if g_nsv_ids[cp] == g_nsv_crib_ids[cp] { cp = cp + 1 } else { go = 0 } } }
703 }
704 // stale-h1 guard: if the snapshot covers the WHOLE prompt (identical prompt, e.g. best-of-N resample),
705 // still re-run the LAST prompt token so g_nsv_h1 is the state after token nprompt-1, not a stale gen state.
706 // Rewriting KV row nprompt-1 with the same values is harmless; skipping it leaves h1 wrong.
707 if cp >= nprompt { cp = nprompt - 1 }
708 i = cp
709 }
710 while i < nprompt {
711 dequant_row(g_nsv_buf, g_nsv_mt[4], g_nsv_mt[5], g_nsv_ids[i], ne, g_nsv_x1, g_nsv_tmp)
712 nsv_step(i, mode)
713 i = i + 1
714 }
715 if us == 0 {
716 var snl: i64 = prefix_len
717 if snl > nprompt { snl = nprompt }
718 if snl > 0 { nsv_kv_snapshot(snl) }
719 }
720 rmsnorm_gamma_row_q24(g_nsv_h1, g_nsv_gout, 0, ne, g_nsv_normed, 0)
721 var next: i64 = nsv_next_token(np)
722 var T: i64 = nprompt
723 g_nsv_ids[T]=next
724 T=T+1
725 var ngen: i64 = 1
726 var stop: i64 = 0
727 if next==NSV_EOS1 { stop=1; meta[4]=1 }
728 if next==NSV_EOS2 { stop=1; meta[4]=1 }
729 if stop == 0 { ep[1] = nsv_emit_piece(next, ep) }
730 while stop == 0 {
731 if ngen >= max_new { stop = 1 } else { if T >= NSV_MAXT { stop = 1 } else {
732 let pos: i64 = T - 1
733 dequant_row(g_nsv_buf, g_nsv_mt[4], g_nsv_mt[5], g_nsv_ids[pos], ne, g_nsv_x1, g_nsv_tmp)
734 nsv_step(pos, mode)
735 rmsnorm_gamma_row_q24(g_nsv_h1, g_nsv_gout, 0, ne, g_nsv_normed, 0)
736 next = nsv_next_token(np)
737 g_nsv_ids[T]=next
738 T=T+1
739 ngen=ngen+1
740 if next==NSV_EOS1 { stop=1; meta[4]=1 }
741 if next==NSV_EOS2 { stop=1; meta[4]=1 }
742 if meta[4] == 0 { ep[1] = nsv_emit_piece(next, ep) }
743 } }
744 }
745 let t1: i64 = sys_now_ms()
746 meta[1]=ngen
747 meta[2]=t1-t0
748 if ngen > 0 { meta[3]=(t1-t0)/(nprompt+ngen) }
749 return ep[1]
750}
751
752// ---- GPU ORACLE socket client (e4) -- ⚠BENCH LANE ONLY, NEVER THE RUN LANE (operator law
753// 2026-07-15: "sovereign from the hardware first byte up"; C/libcuda = benchmark oracle like
754// WARP/fxc/gcc). mode 2 is invoked ONLY by in-process gates (nx_gpu_embed_gate) to grade the
755// sovereign CPU path against the resident-weight GPU oracle; the daemon HTTP surface cannot
756// select it. The production /embed and /gen paths are 100%-sovereign CPU until the NishiLang
757// GPU driver (#22) exists. Protocol per token: send [pos=-(i+1):i64][x1: ne i64] ->
758// recv [normed: ne i64]. NO silent fallback: absent oracle = a loud error.
759func nsv_gwall(fd: i64, buf: *u8, count: i64) -> i64 {
760 var off: i64 = 0
761 while off < count {
762 let q: *u8 = buf + off
763 let w: i64 = sys_write(fd, q, count - off)
764 if w <= 0 { return 0 - 1 }
765 off = off + w
766 }
767 return 0
768}
769
770func nsv_grall(fd: i64, buf: *u8, count: i64) -> i64 {
771 var off: i64 = 0
772 while off < count {
773 let q: *u8 = buf + off
774 let r: i64 = sys_read(fd, q, count - off)
775 if r <= 0 { return 0 - 1 }
776 off = off + r
777 }
778 return 0
779}
780
781func nsv_gpu_connect() -> i64 {
782 let fd: i64 = sys_socket(1, 1, 0)
783 if fd < 0 { return 0 - 1 }
784 let sa: *u8 = sys_mmap(128) as *u8
785 sa[0] = 1 as u8
786 sa[1] = 0 as u8
787 let path: *u8 = "/home/elderwesto/nx_stage/nx_gpu.sock" as *u8
788 var i: i64 = 0
789 while path[i] != (0 as u8) { sa[2 + i] = path[i]; i = i + 1 }
790 let cr: i64 = sys_connect(fd, sa, 110)
791 if cr < 0 { sys_close(fd); return 0 - 2 }
792 return fd
793}
794
795// EMBEDDING (jina-code-embeddings recipe, arXiv:2508.21290): a code/text embedding is the LAST-TOKEN
796// pooled FINAL-NORM hidden state == exactly g_nsv_normed after the sequential prefill. No ChatML, no
797// generation -- the caller prepends the task instruction prefix (nl2code/qa/code2code/...) to the text.
798// Fresh sequence by construction: prefill restarts at pos=0 (KV rows 0..n-1 overwritten; causal attention
799// never reads beyond pos -> no state leak between embeds; same semantics as the GPU serve pos==0).
800// outvec receives ne i64s (Q24 scale). Returns n_prompt_tokens (>0) or negative error.
801func nsv_embed(text: *u8, tlen: i64, mode: i64, outvec: *i64) -> i64 {
802 if g_nsv_mt[6] != 1 { return 0-9 }
803 if tlen < 1 { return 0-1 }
804 let nprompt: i64 = tk_bpe_encode(g_nsv_buf, g_nsv_mt[0], g_nsv_mt[1], g_nsv_mt[2], g_nsv_mt[3], text, tlen, g_nsv_tokp, g_nsv_tokl, g_nsv_ids)
805 if nprompt < 1 { return 0-2 }
806 if nprompt >= NSV_MAXT - 2 { return 0-3 }
807 let ne: i64 = g_nsv_cfgA[1]
808 if mode == 2 {
809 // GPU backend: forward+norm run on the resident-weight server, bit-exact vs the CPU i8 path
810 // (gate nx_gpu_embed_gate). Reply lands directly in outvec; the last token's reply stays.
811 let gs: i64 = nsv_gpu_connect()
812 if gs < 0 { return 0 - 10 }
813 let posb: *i64 = sys_mmap(8) as *i64
814 var k: i64 = 0
815 while k < nprompt {
816 dequant_row(g_nsv_buf, g_nsv_mt[4], g_nsv_mt[5], g_nsv_ids[k], ne, g_nsv_x1, g_nsv_tmp)
817 posb[0] = 0 - (k + 1)
818 if nsv_gwall(gs, posb as *u8, 8) != 0 { sys_close(gs); return 0 - 11 }
819 if nsv_gwall(gs, g_nsv_x1 as *u8, ne * 8) != 0 { sys_close(gs); return 0 - 11 }
820 if nsv_grall(gs, outvec as *u8, ne * 8) != 0 { sys_close(gs); return 0 - 12 }
821 k = k + 1
822 }
823 sys_close(gs)
824 return nprompt
825 }
826 var i: i64 = 0
827 while i < nprompt {
828 dequant_row(g_nsv_buf, g_nsv_mt[4], g_nsv_mt[5], g_nsv_ids[i], ne, g_nsv_x1, g_nsv_tmp)
829 nsv_step(i, mode)
830 i = i + 1
831 }
832 rmsnorm_gamma_row_q24(g_nsv_h1, g_nsv_gout, 0, ne, g_nsv_normed, 0)
833 var j: i64 = 0
834 while j < ne { outvec[j] = g_nsv_normed[j]; j = j + 1 }
835 return nprompt
836}
837
838// ---- HTTP layer (in-process; the daemon shell only moves bytes) ----
839func nsv_resp(resb: *u8, rescap: i64, code: i64, ctype: *u8, body: *u8, blen: i64) -> i64 {
840 var o: i64 = 0
841 o = nsv_cat(resb, o, "HTTP/1.1 " as *u8)
842 o = nsv_catn(resb, o, code)
843 if code == 200 { o = nsv_cat(resb, o, " OK" as *u8) } else { o = nsv_cat(resb, o, " X" as *u8) }
844 o = nsv_cat(resb, o, "\r\nContent-Type: " as *u8)
845 o = nsv_cat(resb, o, ctype)
846 o = nsv_cat(resb, o, "\r\nContent-Length: " as *u8)
847 o = nsv_catn(resb, o, blen)
848 o = nsv_cat(resb, o, "\r\nConnection: close\r\n\r\n" as *u8)
849 if o + blen < rescap { o = nsv_catb(resb, o, body, blen) }
850 return o
851}
852// JSON-escape ONE byte into dst at o; returns new o (early-return ladder -- no else-chains).
853func nsv_jesc1(dst: *u8, o: i64, c: i64) -> i64 {
854 if c == 34 { dst[o]=92 as u8; dst[o+1]=34 as u8; return o+2 }
855 if c == 92 { dst[o]=92 as u8; dst[o+1]=92 as u8; return o+2 }
856 if c == 10 { dst[o]=92 as u8; dst[o+1]=110 as u8; return o+2 }
857 if c == 13 { dst[o]=92 as u8; dst[o+1]=114 as u8; return o+2 }
858 if c == 9 { dst[o]=92 as u8; dst[o+1]=116 as u8; return o+2 }
859 if c < 32 { dst[o]=32 as u8; return o+1 }
860 dst[o]=c as u8
861 return o+1
862}
863// JSON-escape src[0,n) into dst at off
864func nsv_jesc(dst: *u8, off: i64, src: *u8, n: i64) -> i64 {
865 var o: i64 = off
866 var i: i64 = 0
867 while i < n { o = nsv_jesc1(dst, o, src[i] & 0xff); i = i + 1 }
868 return o
869}
870// find "key": in body[0,n); return index just after the colon, -1 if absent.
871func nsv_jkey(body: *u8, n: i64, key: *u8) -> i64 {
872 let kl: i64 = nsv_slen(key)
873 var i: i64 = 0
874 while i + kl + 3 < n {
875 if body[i] == (34 as u8) {
876 var k: i64 = 0
877 var ok: i64 = 1
878 while k < kl { if body[i+1+k] != key[k] { ok = 0; k = kl } else { k = k + 1 } }
879 if ok == 1 { if body[i+1+kl] == (34 as u8) {
880 var j: i64 = i + 2 + kl
881 while j < n { if body[j] == (58 as u8) { return j + 1 } if body[j] == (34 as u8) { j = n } else { j = j + 1 } }
882 } }
883 }
884 i = i + 1
885 }
886 return 0 - 1
887}
888// extract a JSON string value starting at/after p (skips ws to the opening quote); unescapes into dst; returns len (-1 if absent).
889func nsv_jstr(body: *u8, n: i64, p: i64, dst: *u8, dcap: i64) -> i64 {
890 var i: i64 = p
891 while i < n { if body[i] == (34 as u8) { i = i + 1; var o: i64 = 0
892 while i < n {
893 let c: i64 = body[i] & 0xff
894 if c == 34 { return o }
895 if c == 92 { if i + 1 < n {
896 let e: i64 = body[i+1] & 0xff
897 var w: i64 = e
898 if e == 110 { w = 10 }
899 if e == 116 { w = 9 }
900 if e == 114 { w = 13 }
901 if o < dcap { dst[o] = w as u8; o = o + 1 }
902 i = i + 2
903 } else { i = i + 1 } } else {
904 if o < dcap { dst[o] = c as u8; o = o + 1 }
905 i = i + 1
906 }
907 }
908 return 0 - 1
909 }
910 if body[i] == (32 as u8) { i = i + 1 } else { if body[i] == (9 as u8) { i = i + 1 } else { return 0 - 1 } }
911 }
912 return 0 - 1
913}
914// extract a JSON integer at/after p; returns value (def if absent).
915func nsv_jint(body: *u8, n: i64, p: i64, def: i64) -> i64 {
916 if p < 0 { return def }
917 var i: i64 = p
918 var skipping: i64 = 1
919 while skipping == 1 {
920 if i >= n { skipping = 0 } else {
921 if body[i] == (32 as u8) { i = i + 1 } else { skipping = 0 }
922 }
923 }
924 var v: i64 = 0
925 var any: i64 = 0
926 var going: i64 = 1
927 while going == 1 {
928 if i >= n { going = 0 } else {
929 let c: i64 = body[i] & 0xff
930 if c >= 48 { if c <= 57 { v = v * 10 + (c - 48); any = 1; i = i + 1 } else { going = 0 } } else { going = 0 }
931 }
932 }
933 if any == 0 { return def }
934 return v
935}
936
937// the app page: served at GET /. NOTE: NishiLang literals cannot carry the two banned bytes, so the page uses
938// rgb() colors, class selectors and no doctype -- functional, clean, dark.
939func nsv_page(dst: *u8, cap: i64) -> i64 {
940 var o: i64 = 0
941 o = nsv_cat(dst, o, "<html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>Nishi No-Float LLM</title><style>body{font-family:system-ui,Segoe UI,Roboto,sans-serif;background:rgb(16,17,22);color:rgb(226,228,235);max-width:760px;margin:4vh auto;padding:0 20px;line-height:1.55}h1{font-size:1.4rem;margin-bottom:.2rem}p.sub{color:rgb(150,155,170);font-size:.9rem;margin-top:0}textarea{width:100%;min-height:90px;background:rgb(28,30,38);color:rgb(230,232,240);border:1px solid rgb(60,63,75);border-radius:8px;padding:10px;font-size:1rem;box-sizing:border-box}select,input{background:rgb(28,30,38);color:rgb(230,232,240);border:1px solid rgb(60,63,75);border-radius:6px;padding:6px 8px}button{background:rgb(58,110,235);color:white;border:none;border-radius:8px;padding:9px 18px;font-size:1rem;cursor:pointer}button:disabled{opacity:.5}.row{display:flex;gap:10px;align-items:center;margin:10px 0;flex-wrap:wrap}.out{white-space:pre-wrap;background:rgb(24,26,33);border:1px solid rgb(55,58,70);border-radius:8px;padding:12px;min-height:60px;margin-top:8px;font-size:1.02rem}.st{color:rgb(140,200,150);font-size:.85rem;min-height:1.2em}.ft{margin-top:2rem;color:rgb(120,124,138);font-size:.78rem}</style></head><body><h1>Nishi No-Float LLM</h1><p class=\"sub\">Qwen2.5-0.5B-Instruct on the sovereign 100 percent integer inference stack. Deterministic: same prompt, same bytes.</p><textarea class=\"pr\" placeholder=\"Type a prompt...\">The capital of France is</textarea><div class=\"row\"><label>tokens <input class=\"mn\" type=\"number\" value=\"24\" min=\"1\" max=\"96\" style=\"width:70px\"></label><label>mode <select class=\"md\"><option value=\"i32\">i32 lossless</option><option value=\"i8\">i8 fast</option></select></label><label>temp <select class=\"tp\"><option value=\"0\">0 (greedy, bit-exact)</option><option value=\"700\">0.7</option><option value=\"800\">0.8</option><option value=\"1000\">1.0</option><option value=\"1200\">1.2</option></select></label><label>seed <input class=\"sd\" type=\"number\" value=\"12345\" style=\"width:90px\"></label><button class=\"go\" onclick=\"go()\">Generate</button></div><div class=\"st\"></div><div class=\"out\"></div><div class=\"ft\">endpoints: POST /gen · GET /health · GET /api — served by nx_nofloat_serve (no gcc, no python, no float)</div><script>async function go(){var b=document.querySelector('.go');var st=document.querySelector('.st');var out=document.querySelector('.out');var t=document.querySelector('.pr').value;var mn=parseInt(document.querySelector('.mn').value);var md=document.querySelector('.md').value;var tp=parseInt(document.querySelector('.tp').value);var sd=parseInt(document.querySelector('.sd').value);b.disabled=true;st.textContent='thinking...';out.textContent=t;try{var r=await fetch('/gen',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({prompt:t,max_new:mn,mode:md,temp:tp,seed:sd,stream:1})});var rd=r.body.getReader();var dec=new TextDecoder();var acc='';var SEP=String.fromCharCode(10)+String.fromCharCode(10);var going=true;while(going){var ch=await rd.read();if(ch.done){going=false}else{acc=acc+dec.decode(ch.value,{stream:true});var parts=acc.split(SEP);acc=parts.pop();for(var pi=0;pi<parts.length;pi=pi+1){var ln=parts[pi];if(ln.indexOf('data: ')==0){var j=JSON.parse(ln.slice(6));if(j.piece){out.textContent=out.textContent+j.piece}if(j.done==1){if(j.ok==1){st.textContent=j.gen_tokens+' tokens · '+j.ms_per_token+' ms/token · '+md+(tp>0?' · temp '+(tp/1000)+' seed '+sd:' · greedy')+(j.eos==1?' · eos':'')}else{st.textContent='error '+j.err}}}}}}}catch(e){st.textContent='request failed: '+e}b.disabled=false;}</script></body></html>" as *u8)
942 return o
943}
944
945// parse a POST /gen request body into gp: [0]=prompt [1]=plen [2]=max_new [3]=mode(0=i32,1=i8)
946// [8]=temp_pm(0=greedy) [9]=top_p_pm [10]=top_k [11]=seed [12]=stream(0/1). 0 ok, -1 bad.
947func nsv_parse_gen(req: *u8, rn: i64, gp: *i64) -> i64 {
948 var hb: i64 = 0 - 1
949 var i: i64 = 0
950 while i + 3 < rn {
951 if req[i]==(13 as u8) { if req[i+1]==(10 as u8) { if req[i+2]==(13 as u8) { if req[i+3]==(10 as u8) { hb = i + 4; i = rn } } } }
952 i = i + 1
953 }
954 if hb < 0 { return 0 - 1 }
955 let bb: *u8 = ((req as i64) + hb) as *u8
956 let bn: i64 = rn - hb
957 let prompt: *u8 = sys_mmap(32768)
958 let kp: i64 = nsv_jkey(bb, bn, "prompt" as *u8)
959 var pl2: i64 = 0 - 1
960 if kp >= 0 { pl2 = nsv_jstr(bb, bn, kp, prompt, 32760) }
961 if pl2 < 1 { return 0 - 1 }
962 gp[0]=prompt as i64
963 gp[1]=pl2
964 gp[2]=nsv_jint(bb, bn, nsv_jkey(bb, bn, "max_new" as *u8), 24)
965 var mode: i64 = 0
966 let kd: i64 = nsv_jkey(bb, bn, "mode" as *u8)
967 if kd >= 0 {
968 let ms: *u8 = sys_mmap(16)
969 let ml: i64 = nsv_jstr(bb, bn, kd, ms, 8)
970 if ml == 2 { if ms[0]==(105 as u8) { if ms[1]==(56 as u8) { mode = 1 } } }
971 }
972 gp[3]=mode
973 gp[8]=nsv_jint(bb, bn, nsv_jkey(bb, bn, "temp" as *u8), 0)
974 gp[9]=nsv_jint(bb, bn, nsv_jkey(bb, bn, "top_p" as *u8), 950)
975 gp[10]=nsv_jint(bb, bn, nsv_jkey(bb, bn, "top_k" as *u8), 64)
976 gp[11]=nsv_jint(bb, bn, nsv_jkey(bb, bn, "seed" as *u8), 12345)
977 // SLOT-COLLISION FIX (2026-07-15): "stream" used to land in gp[12], but the forge-era nsv_generate
978 // contract made gp[12] = CHATML -- so every streamed request silently chatml-wrapped (caught by the
979 // serve gate T6: streamed 'The capital of France is' returned chat-'Paris', 13 prompt tokens, not the
980 // raw ' Paris' continuation, 5 tokens). Streaming discriminator now gp[13]; gp[12] = the EXPLICIT
981 // "chat" body key (default 0 = raw) -- both transports get both behaviors, explicitly.
982 gp[12]=nsv_jint(bb, bn, nsv_jkey(bb, bn, "chat" as *u8), 0)
983 gp[13]=nsv_jint(bb, bn, nsv_jkey(bb, bn, "stream" as *u8), 0)
984 return 0
985}
986// jina-code-embeddings task instruction prefixes (VERBATIM from the jina-code-embeddings-0.5b model card /
987// arXiv:2508.21290 -- protocol constants, cited not invented). Task selected by (len, first byte):
988// qa=2, code2code=9, code2completion=15, code2nl=7+'c', default nl2code. kq=1 -> query prefix, else passage.
989func nsv_embed_prefix(task: *u8, tl: i64, kq: i64) -> *u8 {
990 if tl == 2 {
991 if kq == 1 { return "Find the most relevant answer given the following question:\n" as *u8 }
992 return "Candidate answer:\n" as *u8
993 }
994 if tl == 9 {
995 if kq == 1 { return "Find an equivalent code snippet given the following code snippet:\n" as *u8 }
996 return "Candidate code snippet:\n" as *u8
997 }
998 if tl == 15 {
999 if kq == 1 { return "Find the most relevant completion given the following start of code snippet:\n" as *u8 }
1000 return "Candidate completion:\n" as *u8
1001 }
1002 if tl == 7 { if task[0] == (99 as u8) {
1003 if kq == 1 { return "Find the most relevant comment given the following code snippet:\n" as *u8 }
1004 return "Candidate comment:\n" as *u8
1005 } }
1006 if kq == 1 { return "Find the most relevant code snippet given the following query:\n" as *u8 }
1007 return "Candidate code snippet:\n" as *u8
1008}
1009
1010// parse POST /embed body {"text","task","kind","mode"} -> ep: [0]=text ptr [1]=text len [2]=mode(1=i8 default)
1011// [3]=kind_q(1=query default) [4]=task ptr [5]=task len (0 = default nl2code). 0 ok, -1 bad (text required).
1012func nsv_parse_embed(req: *u8, rn: i64, ep: *i64) -> i64 {
1013 var hb: i64 = 0 - 1
1014 var i: i64 = 0
1015 while i + 3 < rn {
1016 if req[i]==(13 as u8) { if req[i+1]==(10 as u8) { if req[i+2]==(13 as u8) { if req[i+3]==(10 as u8) { hb = i + 4; i = rn } } } }
1017 i = i + 1
1018 }
1019 if hb < 0 { return 0 - 1 }
1020 let bb: *u8 = ((req as i64) + hb) as *u8
1021 let bn: i64 = rn - hb
1022 let text: *u8 = sys_mmap(8192)
1023 let kt: i64 = nsv_jkey(bb, bn, "text" as *u8)
1024 var tl: i64 = 0 - 1
1025 if kt >= 0 { tl = nsv_jstr(bb, bn, kt, text, 8100) }
1026 if tl < 1 { return 0 - 1 }
1027 ep[0]=text as i64
1028 ep[1]=tl
1029 var mode: i64 = 1
1030 let kd: i64 = nsv_jkey(bb, bn, "mode" as *u8)
1031 if kd >= 0 {
1032 let ms: *u8 = sys_mmap(16)
1033 let ml: i64 = nsv_jstr(bb, bn, kd, ms, 8)
1034 // NOTE: mode 2 (GPU oracle) is BENCH-ONLY and deliberately NOT reachable from the HTTP
1035 // surface -- the run lane is sovereign CPU end-to-end (operator law 2026-07-15: C/libcuda
1036 // = benchmark oracle, never the run lane). Gates drive mode 2 in-process.
1037 if ml == 3 { mode = 0 }
1038 }
1039 ep[2]=mode
1040 var kq: i64 = 1
1041 let kk: i64 = nsv_jkey(bb, bn, "kind" as *u8)
1042 if kk >= 0 {
1043 let ks: *u8 = sys_mmap(16)
1044 let kl: i64 = nsv_jstr(bb, bn, kk, ks, 12)
1045 if kl > 0 { if ks[0]==(112 as u8) { kq = 0 } }
1046 }
1047 ep[3]=kq
1048 let task: *u8 = sys_mmap(32)
1049 var tkl: i64 = 0
1050 let kta: i64 = nsv_jkey(bb, bn, "task" as *u8)
1051 if kta >= 0 {
1052 let r: i64 = nsv_jstr(bb, bn, kta, task, 24)
1053 if r > 0 { tkl = r }
1054 }
1055 ep[4]=task as i64
1056 ep[5]=tkl
1057 return 0
1058}
1059
1060// STREAMING route: if the request is POST /gen with "stream":1, serve it as Server-Sent Events DIRECTLY on
1061// fd (headers -> start frame -> one data frame per token from nsv_generate -> done frame with meta) and
1062// return 1. Any other request returns 0 (caller falls through to the buffered nsv_handle). The daemon calls
1063// this FIRST; the gate drives it with a file fd -- same bytes either way.
1064func nsv_handle_stream(fd: i64, req: *u8, rn: i64) -> i64 {
1065 var is_post: i64 = 0
1066 if rn > 5 { if req[0]==(80 as u8) { is_post = 1 } }
1067 if is_post == 0 { return 0 }
1068 if req[6] != (103 as u8) { return 0 }
1069 let gp: *i64 = sys_mmap(16*8) as *i64
1070 let prc: i64 = nsv_parse_gen(req, rn, gp)
1071 if prc != 0 { return 0 }
1072 if gp[13] != 1 { return 0 }
1073 let hdrs: *u8 = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache\r\nConnection: close\r\n\r\n" as *u8
1074 var hl: i64 = nsv_slen(hdrs)
1075 var w: i64 = 0
1076 while w < hl { let k1: i64 = sys_write(fd, ((hdrs as i64)+w) as *u8, hl-w); if k1 <= 0 { w = hl } else { w = w + k1 } }
1077 let text: *u8 = sys_mmap(65536)
1078 let meta: *i64 = sys_mmap(8*8) as *i64
1079 gp[4]=text as i64
1080 gp[5]=65000
1081 gp[6]=meta as i64
1082 gp[7]=fd
1083 let tl: i64 = nsv_generate(gp)
1084 let fin: *u8 = sys_mmap(1024)
1085 var fo: i64 = 0
1086 if tl < 0 {
1087 fo = nsv_cat(fin, 0, "data: {\"done\":1,\"ok\":0,\"err\":" as *u8)
1088 fo = nsv_catn(fin, fo, meta[5])
1089 fo = nsv_cat(fin, fo, "}\n\n" as *u8)
1090 } else {
1091 fo = nsv_cat(fin, 0, "data: {\"done\":1,\"ok\":1,\"prompt_tokens\":" as *u8)
1092 fo = nsv_catn(fin, fo, meta[0])
1093 fo = nsv_cat(fin, fo, ",\"gen_tokens\":" as *u8)
1094 fo = nsv_catn(fin, fo, meta[1])
1095 fo = nsv_cat(fin, fo, ",\"ms_per_token\":" as *u8)
1096 fo = nsv_catn(fin, fo, meta[3])
1097 fo = nsv_cat(fin, fo, ",\"eos\":" as *u8)
1098 fo = nsv_catn(fin, fo, meta[4])
1099 fo = nsv_cat(fin, fo, "}\n\n" as *u8)
1100 }
1101 w = 0
1102 while w < fo { let k2: i64 = sys_write(fd, ((fin as i64)+w) as *u8, fo-w); if k2 <= 0 { w = fo } else { w = w + k2 } }
1103 return 1
1104}
1105
1106// route + serve one request. returns response length in resb.
1107func nsv_handle(req: *u8, rn: i64, resb: *u8, rescap: i64) -> i64 {
1108 let body: *u8 = sys_mmap(65536)
1109 var blen: i64 = 0
1110 // method + path
1111 var is_get: i64 = 0
1112 var is_post: i64 = 0
1113 if rn > 4 { if req[0]==(71 as u8) { is_get=1 } }
1114 if rn > 5 { if req[0]==(80 as u8) { is_post=1 } }
1115 var ps: i64 = 4
1116 if is_post == 1 { ps = 5 }
1117 var pe: i64 = ps
1118 var scanning: i64 = 1
1119 while scanning == 1 {
1120 if pe >= rn { scanning = 0 } else {
1121 if req[pe]==(32 as u8) { scanning = 0 } else { pe = pe + 1 }
1122 }
1123 }
1124 let plen: i64 = pe - ps
1125 // GET /
1126 if is_get == 1 { if plen == 1 { if req[ps]==(47 as u8) {
1127 let page: *u8 = sys_mmap(16384)
1128 let pn: i64 = nsv_page(page, 16384)
1129 return nsv_resp(resb, rescap, 200, "text/html; charset=utf-8" as *u8, page, pn)
1130 } } }
1131 // GET /health
1132 if is_get == 1 { if plen == 7 { if req[ps+1]==(104 as u8) {
1133 var o: i64 = 0
1134 o = nsv_cat(body, o, "{\"ok\":" as *u8)
1135 o = nsv_catn(body, o, g_nsv_mt[6])
1136 o = nsv_cat(body, o, ",\"model\":\"" as *u8)
1137 o = nsv_jesc(body, o, g_nsv_mpath, nsv_slen(g_nsv_mpath))
1138 o = nsv_cat(body, o, "\",\"modes\":[\"i32\",\"i8\"],\"maxt\":" as *u8)
1139 o = nsv_catn(body, o, NSV_MAXT)
1140 o = nsv_cat(body, o, ",\"init_ms\":" as *u8)
1141 o = nsv_catn(body, o, g_nsv_mt[7])
1142 o = nsv_cat(body, o, "}" as *u8)
1143 return nsv_resp(resb, rescap, 200, "application/json" as *u8, body, o)
1144 } } }
1145 // GET /api
1146 if is_get == 1 { if plen == 4 { if req[ps+1]==(97 as u8) {
1147 let o: i64 = nsv_cat(body, 0, "{\"organ\":\"nx_nofloat_serve\",\"endpoints\":[{\"m\":\"POST\",\"p\":\"/gen\",\"body\":{\"prompt\":\"str\",\"max_new\":\"int 1-96 (default 24)\",\"mode\":\"i32|i8\",\"stream\":\"0|1 SSE\",\"chat\":\"0|1 ChatML wrap\"}},{\"m\":\"POST\",\"p\":\"/embed\",\"body\":{\"text\":\"str required <=8100B\",\"task\":\"nl2code|qa|code2code|code2nl|code2completion (default nl2code)\",\"kind\":\"query|passage (default query)\",\"mode\":\"i8|i32 (default i8)\"},\"returns\":\"dim=896 q24 int vector (last-token pooled final-norm hidden, arXiv 2508.21290)\"},{\"m\":\"GET\",\"p\":\"/health\"},{\"m\":\"GET\",\"p\":\"/\"}],\"stack\":\"sovereign 100pct-integer Qwen2.5-0.5B, dequant-once i32 lossless + i8 SIMD fast, KV-cached greedy\"}" as *u8)
1148 return nsv_resp(resb, rescap, 200, "application/json" as *u8, body, o)
1149 } } }
1150 // POST /gen
1151 if is_post == 1 { if plen == 4 { if req[ps+1]==(103 as u8) {
1152 let gp: *i64 = sys_mmap(16*8) as *i64
1153 let prc: i64 = nsv_parse_gen(req, rn, gp)
1154 if prc != 0 {
1155 let o: i64 = nsv_cat(body, 0, "{\"ok\":0,\"err\":1}" as *u8)
1156 return nsv_resp(resb, rescap, 400, "application/json" as *u8, body, o)
1157 }
1158 let text: *u8 = sys_mmap(65536)
1159 let meta: *i64 = sys_mmap(8*8) as *i64
1160 gp[4]=text as i64
1161 gp[5]=65000
1162 gp[6]=meta as i64
1163 gp[7]=0-1
1164 let mode: i64 = gp[3]
1165 let tl: i64 = nsv_generate(gp)
1166 if tl < 0 {
1167 var o: i64 = nsv_cat(body, 0, "{\"ok\":0,\"err\":" as *u8)
1168 o = nsv_catn(body, o, meta[5])
1169 o = nsv_cat(body, o, "}" as *u8)
1170 return nsv_resp(resb, rescap, 400, "application/json" as *u8, body, o)
1171 }
1172 var o: i64 = 0
1173 o = nsv_cat(body, o, "{\"ok\":1,\"mode\":\"" as *u8)
1174 if mode == 1 { o = nsv_cat(body, o, "i8" as *u8) } else { o = nsv_cat(body, o, "i32" as *u8) }
1175 o = nsv_cat(body, o, "\",\"prompt_tokens\":" as *u8)
1176 o = nsv_catn(body, o, meta[0])
1177 o = nsv_cat(body, o, ",\"gen_tokens\":" as *u8)
1178 o = nsv_catn(body, o, meta[1])
1179 o = nsv_cat(body, o, ",\"ms_total\":" as *u8)
1180 o = nsv_catn(body, o, meta[2])
1181 o = nsv_cat(body, o, ",\"ms_per_token\":" as *u8)
1182 o = nsv_catn(body, o, meta[3])
1183 o = nsv_cat(body, o, ",\"eos\":" as *u8)
1184 o = nsv_catn(body, o, meta[4])
1185 o = nsv_cat(body, o, ",\"temp\":" as *u8)
1186 o = nsv_catn(body, o, gp[8])
1187 o = nsv_cat(body, o, ",\"seed\":" as *u8)
1188 o = nsv_catn(body, o, gp[11])
1189 o = nsv_cat(body, o, ",\"text\":\"" as *u8)
1190 o = nsv_jesc(body, o, text, tl)
1191 o = nsv_cat(body, o, "\"}" as *u8)
1192 return nsv_resp(resb, rescap, 200, "application/json" as *u8, body, o)
1193 } } }
1194 // POST /embed (jina-code-embeddings recipe arXiv:2508.21290: the embedding IS the last-token pooled
1195 // final-norm hidden state; instruction prefix prepended server-side). Returns the raw Q24 int vector --
1196 // cosine/ranking is the caller's (or the index organ's) job, integer math end to end.
1197 if is_post == 1 { if plen == 6 { if req[ps+1]==(101 as u8) {
1198 if g_nsv_mt[6] != 1 {
1199 let o: i64 = nsv_cat(body, 0, "{\"ok\":0,\"err\":9}" as *u8)
1200 return nsv_resp(resb, rescap, 503, "application/json" as *u8, body, o)
1201 }
1202 let ep: *i64 = sys_mmap(8*8) as *i64
1203 let erc: i64 = nsv_parse_embed(req, rn, ep)
1204 if erc != 0 {
1205 let o: i64 = nsv_cat(body, 0, "{\"ok\":0,\"err\":1}" as *u8)
1206 return nsv_resp(resb, rescap, 400, "application/json" as *u8, body, o)
1207 }
1208 let pre: *u8 = nsv_embed_prefix(ep[4] as *u8, ep[5], ep[3])
1209 let txt: *u8 = sys_mmap(NSV_MAXIN)
1210 var l: i64 = nsv_cat(txt, 0, pre)
1211 l = nsv_catb(txt, l, ep[0] as *u8, ep[1])
1212 let ne: i64 = g_nsv_cfgA[1]
1213 let vec: *i64 = sys_mmap(ne*8) as *i64
1214 let t0: i64 = sys_now_ms()
1215 let n: i64 = nsv_embed(txt, l, ep[2], vec)
1216 let t1: i64 = sys_now_ms()
1217 if n < 1 {
1218 var o: i64 = nsv_cat(body, 0, "{\"ok\":0,\"err\":" as *u8)
1219 o = nsv_catn(body, o, n)
1220 o = nsv_cat(body, o, "}" as *u8)
1221 return nsv_resp(resb, rescap, 400, "application/json" as *u8, body, o)
1222 }
1223 var o: i64 = 0
1224 o = nsv_cat(body, o, "{\"ok\":1,\"dim\":" as *u8)
1225 o = nsv_catn(body, o, ne)
1226 o = nsv_cat(body, o, ",\"ntok\":" as *u8)
1227 o = nsv_catn(body, o, n)
1228 o = nsv_cat(body, o, ",\"ms\":" as *u8)
1229 o = nsv_catn(body, o, t1 - t0)
1230 o = nsv_cat(body, o, ",\"scale\":\"q24\",\"mode\":\"" as *u8)
1231 if ep[2] == 1 { o = nsv_cat(body, o, "i8" as *u8) } else { o = nsv_cat(body, o, "i32" as *u8) }
1232 o = nsv_cat(body, o, "\",\"vec\":[" as *u8)
1233 var vi: i64 = 0
1234 while vi < ne {
1235 if vi > 0 { o = nsv_cat(body, o, "," as *u8) }
1236 o = nsv_catn(body, o, vec[vi])
1237 vi = vi + 1
1238 }
1239 o = nsv_cat(body, o, "]}" as *u8)
1240 return nsv_resp(resb, rescap, 200, "application/json" as *u8, body, o)
1241 } } }
1242 let o: i64 = nsv_cat(body, 0, "{\"ok\":0,\"err\":404}" as *u8)
1243 return nsv_resp(resb, rescap, 404, "application/json" as *u8, body, o)
1244}