From d82fee8bcd60586ff6b651647014eaac1102a80c Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 11:26:56 +0200 Subject: [PATCH 1/8] fix(sm86): regenerate the qsa_prompt_resolver companion after the kv-streaming reseal The kv-streaming merge resealed crates/cuda-driver/src/qsa_prompt_resolver.ptx (0103ee9) after the sm_86 companion set was generated, so the table had no key for the new sm_120 body: the two arch_ptx unit tests failed and the 3080 would have been handed the sm_120 image for the streamed-KV resolver. `sm86_assets.py build` (CUDA 13.2.86) changes only that companion, MANIFEST.json and sm86_table.rs; `sm86_assets.py check` OK (127 companions); leleka-cuda-driver --lib --features cuda-driver,sm86: 349 passed. Co-Authored-By: Claude Opus 5.5 --- crates/cuda-driver/ptx-sm86/MANIFEST.json | 10 +- .../ptx-sm86/qsa_prompt_resolver.ptx | 1048 +++++++++-------- crates/cuda-driver/src/sm86_table.rs | 14 +- 3 files changed, 538 insertions(+), 534 deletions(-) diff --git a/crates/cuda-driver/ptx-sm86/MANIFEST.json b/crates/cuda-driver/ptx-sm86/MANIFEST.json index 97ed358f..6c760a72 100644 --- a/crates/cuda-driver/ptx-sm86/MANIFEST.json +++ b/crates/cuda-driver/ptx-sm86/MANIFEST.json @@ -1624,7 +1624,7 @@ "ptxas": "ok", "recipe": "precise", "recipe_confidence": "entries+flag-mode", - "retarget_rejected": "ptxas /home/para/sm86-work/build/mtp_original_prefill_quant.sm86.ptx, line 34613; error : Feature 'cvt.f16x2.e4m3x2' requires .target sm_89 or higher | ptxas /home/para/sm86-work/build/mtp_original_prefill_quant.sm86.ptx, line 36077; error : Feature 'cvt.f16x2.e4m3x2' requires .target sm_89 or higher | ptxas fatal : Ptx assembly aborted due to errors", + "retarget_rejected": "ptxas /home/para/laptop/sm86-work/build/mtp_original_prefill_quant.sm86.ptx, line 34613; error : Feature 'cvt.f16x2.e4m3x2' requires .target sm_89 or higher | ptxas /home/para/laptop/sm86-work/build/mtp_original_prefill_quant.sm86.ptx, line 36077; error : Feature 'cvt.f16x2.e4m3x2' requires .target sm_89 or higher | ptxas fatal : Ptx assembly aborted due to errors", "rules": [], "sm120_bytes": 1343875, "sm120_nvcc": "13.0.88", @@ -2494,13 +2494,13 @@ "count": 1 } ], - "sm120_bytes": 23782, + "sm120_bytes": 23915, "sm120_nvcc": "13.2.86", "sm120_path": "crates/cuda-driver/src/qsa_prompt_resolver.ptx", - "sm120_sha256": "748a2e0d5fcd12a9d49a20fa1556190b22b0630680c7a4ef398d901f47f471b3", + "sm120_sha256": "8d3ecbaecbf28445ba64485bdff3d91a21d87b85d5939a0152ef2f2414480e22", "sm120_stored_nul": true, - "sm86_bytes": 23781, - "sm86_sha256": "2447167293973383cb42afd73fc280b14f679bae30ad84764ed74bd07d2a6ca8" + "sm86_bytes": 23914, + "sm86_sha256": "32d96ca6a72f40eda21d51d9f4d4d377c373c63783cc422910883bb8d8d8b08d" }, { "entries": 5, diff --git a/crates/cuda-driver/ptx-sm86/qsa_prompt_resolver.ptx b/crates/cuda-driver/ptx-sm86/qsa_prompt_resolver.ptx index 348122cf..a459e13b 100644 --- a/crates/cuda-driver/ptx-sm86/qsa_prompt_resolver.ptx +++ b/crates/cuda-driver/ptx-sm86/qsa_prompt_resolver.ptx @@ -26,13 +26,14 @@ .param .u64 .ptr .align 1 leleka_qsa_resolve_param_6, .param .u64 .ptr .align 1 leleka_qsa_resolve_param_7, .param .u64 .ptr .align 1 leleka_qsa_resolve_param_8, - .param .u32 leleka_qsa_resolve_param_9 + .param .u32 leleka_qsa_resolve_param_9, + .param .u64 leleka_qsa_resolve_param_10 ) .maxntid 1024 { - .reg .pred %p<67>; - .reg .b32 %r<117>; - .reg .b64 %rd<106>; + .reg .pred %p<69>; + .reg .b32 %r<121>; + .reg .b64 %rd<104>; // demoted variable .shared .align 4 .u32 _ZZ18leleka_qsa_resolveE7s_nmiss; // demoted variable @@ -41,25 +42,26 @@ .shared .align 4 .u32 _ZZ18leleka_qsa_resolveE5s_cut; // demoted variable .shared .align 4 .b8 _ZZ18leleka_qsa_resolveE9warp_sums[128]; - ld.param.b64 %rd24, [leleka_qsa_resolve_param_0]; - ld.param.b64 %rd25, [leleka_qsa_resolve_param_1]; - ld.param.b64 %rd26, [leleka_qsa_resolve_param_2]; - ld.param.b64 %rd27, [leleka_qsa_resolve_param_3]; - ld.param.b64 %rd28, [leleka_qsa_resolve_param_4]; - ld.param.b64 %rd29, [leleka_qsa_resolve_param_5]; - ld.param.b64 %rd30, [leleka_qsa_resolve_param_6]; - ld.param.b64 %rd22, [leleka_qsa_resolve_param_7]; - ld.param.b64 %rd23, [leleka_qsa_resolve_param_8]; - ld.param.b32 %r35, [leleka_qsa_resolve_param_9]; - cvta.to.global.u64 %rd1, %rd27; - cvta.to.global.u64 %rd2, %rd26; - cvta.to.global.u64 %rd3, %rd25; - cvta.to.global.u64 %rd4, %rd30; - cvta.to.global.u64 %rd5, %rd24; - cvta.to.global.u64 %rd6, %rd29; - cvta.to.global.u64 %rd7, %rd28; - ld.global.b32 %r36, [%rd7]; - add.s32 %r1, %r36, 1; + ld.param.b64 %rd28, [leleka_qsa_resolve_param_0]; + ld.param.b64 %rd29, [leleka_qsa_resolve_param_1]; + ld.param.b64 %rd30, [leleka_qsa_resolve_param_2]; + ld.param.b64 %rd31, [leleka_qsa_resolve_param_3]; + ld.param.b64 %rd32, [leleka_qsa_resolve_param_4]; + ld.param.b64 %rd33, [leleka_qsa_resolve_param_5]; + ld.param.b64 %rd34, [leleka_qsa_resolve_param_6]; + ld.param.b64 %rd25, [leleka_qsa_resolve_param_7]; + ld.param.b64 %rd26, [leleka_qsa_resolve_param_8]; + ld.param.b32 %r36, [leleka_qsa_resolve_param_9]; + ld.param.b64 %rd27, [leleka_qsa_resolve_param_10]; + cvta.to.global.u64 %rd1, %rd31; + cvta.to.global.u64 %rd2, %rd30; + cvta.to.global.u64 %rd3, %rd29; + cvta.to.global.u64 %rd4, %rd34; + cvta.to.global.u64 %rd5, %rd28; + cvta.to.global.u64 %rd6, %rd33; + cvta.to.global.u64 %rd7, %rd32; + ld.global.b32 %r37, [%rd7]; + add.s32 %r1, %r37, 1; mov.u32 %r2, %tid.x; setp.ne.b32 %p1, %r2, 0; @%p1 bra $L__BB0_2; @@ -67,410 +69,423 @@ st.shared.b32 [_ZZ18leleka_qsa_resolveE9s_lookups], 0; $L__BB0_2: bar.sync 0; - setp.lt.s32 %p2, %r35, 1; - mov.b32 %r104, 0; + setp.lt.s32 %p2, %r36, 1; + mov.b32 %r108, 0; @%p2 bra $L__BB0_15; - mul.wide.u32 %rd31, %r2, 4; - cvta.to.global.u64 %rd32, %rd22; - add.s64 %rd8, %rd32, %rd31; - cvta.to.global.u64 %rd9, %rd23; - mov.b32 %r102, 0; - mov.b32 %r104, %r102; + mul.wide.u32 %rd35, %r2, 4; + cvta.to.global.u64 %rd36, %rd25; + add.s64 %rd8, %rd36, %rd35; + cvta.to.global.u64 %rd9, %rd26; + mov.b32 %r106, 0; + mov.b32 %r108, %r106; $L__BB0_4: - shl.b32 %r37, %r102, 2; - mul.wide.u32 %rd33, %r37, 4; - add.s64 %rd34, %rd9, %rd33; - ld.global.b32 %r3, [%rd34+12]; + shl.b32 %r38, %r106, 2; + mul.wide.u32 %rd37, %r38, 4; + add.s64 %rd38, %rd9, %rd37; + ld.global.b32 %r3, [%rd38+12]; setp.ge.s32 %p3, %r2, %r3; @%p3 bra $L__BB0_14; - mul.wide.u32 %rd35, %r102, 8204; - add.s64 %rd101, %rd8, %rd35; - mov.b32 %r103, %r2; + mul.wide.u32 %rd39, %r106, 8204; + add.s64 %rd97, %rd8, %rd39; + mov.b32 %r107, %r2; $L__BB0_6: - ld.global.b32 %r38, [%rd101]; - shr.s32 %r39, %r38, 31; - shr.u32 %r40, %r39, 30; - add.s32 %r41, %r38, %r40; - shr.s32 %r4, %r41, 2; - setp.eq.b32 %p4, %r103, 0; + ld.global.b32 %r39, [%rd97]; + shr.s32 %r40, %r39, 31; + shr.u32 %r41, %r40, 30; + add.s32 %r42, %r39, %r41; + shr.s32 %r4, %r42, 2; + setp.eq.b32 %p4, %r107, 0; @%p4 bra $L__BB0_8; - ld.global.b32 %r42, [%rd101+-4]; - shr.s32 %r43, %r42, 31; - shr.u32 %r44, %r43, 30; - add.s32 %r45, %r42, %r44; - shr.s32 %r46, %r45, 2; - setp.eq.b32 %p5, %r46, %r4; + ld.global.b32 %r43, [%rd97+-4]; + shr.s32 %r44, %r43, 31; + shr.u32 %r45, %r44, 30; + add.s32 %r46, %r43, %r45; + shr.s32 %r47, %r46, 2; + setp.eq.b32 %p5, %r47, %r4; @%p5 bra $L__BB0_13; $L__BB0_8: - add.s32 %r104, %r104, 1; - mul.wide.s32 %rd36, %r4, 4; - add.s64 %rd10, %rd5, %rd36; + add.s32 %r108, %r108, 1; + mul.wide.s32 %rd40, %r4, 4; + add.s64 %rd10, %rd5, %rd40; ld.global.b32 %r5, [%rd10]; setp.lt.s32 %p6, %r5, 0; @%p6 bra $L__BB0_10; - mul.wide.u32 %rd39, %r5, 4; - add.s64 %rd40, %rd2, %rd39; - st.global.b32 [%rd40], %r1; - add.s64 %rd41, %rd1, %rd39; - st.global.b32 [%rd41], 1; + mul.wide.u32 %rd43, %r5, 4; + add.s64 %rd44, %rd2, %rd43; + st.global.b32 [%rd44], %r1; + add.s64 %rd45, %rd1, %rd43; + st.global.b32 [%rd45], 1; bra.uni $L__BB0_13; $L__BB0_10: setp.ne.b32 %p7, %r5, -1; @%p7 bra $L__BB0_13; - atom.relaxed.sys.global.cas.b32 %r47, [%rd10], -1, -2; - setp.ne.b32 %p8, %r47, -1; + atom.relaxed.sys.global.cas.b32 %r48, [%rd10], -1, -2; + setp.ne.b32 %p8, %r48, -1; @%p8 bra $L__BB0_13; - atom.shared.add.u32 %r48, [_ZZ18leleka_qsa_resolveE7s_nmiss], 1; - mul.wide.s32 %rd37, %r48, 4; - add.s64 %rd38, %rd6, %rd37; - st.global.b32 [%rd38], %r4; + atom.shared.add.u32 %r49, [_ZZ18leleka_qsa_resolveE7s_nmiss], 1; + mul.wide.s32 %rd41, %r49, 4; + add.s64 %rd42, %rd6, %rd41; + st.global.b32 [%rd42], %r4; $L__BB0_13: - add.s32 %r103, %r103, 1024; - add.s64 %rd101, %rd101, 4096; - setp.lt.s32 %p9, %r103, %r3; + add.s32 %r107, %r107, 1024; + add.s64 %rd97, %rd97, 4096; + setp.lt.s32 %p9, %r107, %r3; @%p9 bra $L__BB0_6; $L__BB0_14: - add.s32 %r102, %r102, 1; - setp.ne.b32 %p10, %r102, %r35; + add.s32 %r106, %r106, 1; + setp.ne.b32 %p10, %r106, %r36; @%p10 bra $L__BB0_4; $L__BB0_15: - atom.shared.add.u32 %r49, [_ZZ18leleka_qsa_resolveE9s_lookups], %r104; + atom.shared.add.u32 %r50, [_ZZ18leleka_qsa_resolveE9s_lookups], %r108; bar.sync 0; ld.shared.b32 %r6, [_ZZ18leleka_qsa_resolveE7s_nmiss]; - ld.global.b32 %r107, [%rd7+4]; - setp.lt.s32 %p11, %r6, 1; - mov.pred %p66, 0; - mov.b32 %r108, 0; - @%p11 bra $L__BB0_35; + cvt.u32.u64 %r7, %rd27; + ld.global.b32 %r111, [%rd7+4]; + setp.gt.s32 %p68, %r6, 0; + mov.b32 %r112, 0; + min.s32 %r51, %r6, %r7; + setp.lt.s32 %p11, %r51, 1; + @%p11 bra $L__BB0_41; cvt.u64.u32 %rd11, %r2; - and.b32 %r7, %r2, 31; - shr.u32 %r50, %r2, 3; - and.b32 %r51, %r50, 124; - mov.b32 %r52, _ZZ18leleka_qsa_resolveE9warp_sums; - add.s32 %r8, %r52, %r51; - shl.b32 %r53, %r2, 2; - and.b32 %r54, %r53, 124; - add.s32 %r9, %r52, %r54; - add.s32 %r10, %r2, 1; - mov.b32 %r105, 0; - mov.b32 %r108, %r105; + and.b64 %rd12, %rd27, 2147483647; + and.b32 %r8, %r2, 31; + shr.u32 %r52, %r2, 3; + and.b32 %r53, %r52, 124; + mov.b32 %r54, _ZZ18leleka_qsa_resolveE9warp_sums; + add.s32 %r9, %r54, %r53; + shl.b32 %r55, %r2, 2; + and.b32 %r56, %r55, 124; + add.s32 %r10, %r54, %r56; + add.s32 %r11, %r2, 1; + mul.lo.s32 %r12, %r7, 3; + mov.b32 %r109, 0; + mov.b32 %r112, %r109; $L__BB0_17: - mov.b32 %r11, %r105; - cvt.s64.s32 %rd12, %r107; - add.s64 %rd42, %rd12, %rd11; - shr.u64 %rd43, %rd42, 51; - add.s64 %rd44, %rd42, %rd43; - and.b64 %rd45, %rd44, -8192; - sub.s64 %rd46, %rd42, %rd45; - cvt.u32.u64 %r12, %rd46; - shl.b64 %rd13, %rd46, 2; - add.s64 %rd14, %rd2, %rd13; - ld.global.b32 %r13, [%rd14]; - setp.eq.b32 %p12, %r13, %r1; - add.s64 %rd15, %rd1, %rd13; - mov.pred %p65, 0; - @%p12 bra $L__BB0_20; - add.s64 %rd47, %rd3, %rd13; - ld.global.b32 %r55, [%rd47]; - setp.lt.s32 %p13, %r55, 0; - mov.pred %p65, -1; - @%p13 bra $L__BB0_20; - ld.global.b32 %r56, [%rd15]; - setp.eq.b32 %p65, %r56, 0; + cvt.s64.s32 %rd13, %r111; + add.s64 %rd14, %rd13, %rd11; + and.b64 %rd46, %rd14, -4294967296; + setp.ne.b64 %p12, %rd46, 0; + @%p12 bra $L__BB0_19; + cvt.u32.u64 %r57, %rd12; + cvt.u32.u64 %r58, %rd14; + rem.u32 %r59, %r58, %r57; + cvt.u64.u32 %rd98, %r59; + bra.uni $L__BB0_20; +$L__BB0_19: + rem.s64 %rd98, %rd14, %rd12; $L__BB0_20: - setp.lt.u32 %p14, %r7, 16; - setp.lt.u32 %p15, %r7, 8; - setp.lt.u32 %p16, %r7, 4; - setp.lt.u32 %p17, %r7, 2; - setp.eq.b32 %p18, %r7, 0; - setp.ne.b32 %p19, %r7, 31; - selp.b32 %r14, 1, 0, %p65; - shfl.sync.up.b32 %r57|%p20, %r14, 1, 0, -1; - selp.b32 %r58, 0, %r57, %p18; - add.s32 %r59, %r58, %r14; - shfl.sync.up.b32 %r60|%p21, %r59, 2, 0, -1; - selp.b32 %r61, 0, %r60, %p17; - add.s32 %r62, %r61, %r59; - shfl.sync.up.b32 %r63|%p22, %r62, 4, 0, -1; - selp.b32 %r64, 0, %r63, %p16; - add.s32 %r65, %r64, %r62; - shfl.sync.up.b32 %r66|%p23, %r65, 8, 0, -1; - selp.b32 %r67, 0, %r66, %p15; - add.s32 %r68, %r67, %r65; - shfl.sync.up.b32 %r69|%p24, %r68, 16, 0, -1; - selp.b32 %r70, 0, %r69, %p14; - add.s32 %r15, %r70, %r68; - @%p19 bra $L__BB0_22; - st.shared.b32 [%r8], %r15; -$L__BB0_22: - setp.gt.u32 %p25, %r2, 31; + cvt.u32.u64 %r13, %rd98; + shl.b64 %rd15, %rd98, 2; + add.s64 %rd16, %rd2, %rd15; + ld.global.b32 %r14, [%rd16]; + setp.eq.b32 %p13, %r14, %r1; + add.s64 %rd17, %rd1, %rd15; + mov.pred %p67, 0; + @%p13 bra $L__BB0_23; + add.s64 %rd47, %rd3, %rd15; + ld.global.b32 %r60, [%rd47]; + setp.lt.s32 %p14, %r60, 0; + mov.pred %p67, -1; + @%p14 bra $L__BB0_23; + ld.global.b32 %r61, [%rd17]; + setp.eq.b32 %p67, %r61, 0; +$L__BB0_23: + setp.lt.u32 %p15, %r8, 16; + setp.lt.u32 %p16, %r8, 8; + setp.lt.u32 %p17, %r8, 4; + setp.lt.u32 %p18, %r8, 2; + setp.eq.b32 %p19, %r8, 0; + setp.ne.b32 %p20, %r8, 31; + selp.b32 %r15, 1, 0, %p67; + shfl.sync.up.b32 %r62|%p21, %r15, 1, 0, -1; + selp.b32 %r63, 0, %r62, %p19; + add.s32 %r64, %r63, %r15; + shfl.sync.up.b32 %r65|%p22, %r64, 2, 0, -1; + selp.b32 %r66, 0, %r65, %p18; + add.s32 %r67, %r66, %r64; + shfl.sync.up.b32 %r68|%p23, %r67, 4, 0, -1; + selp.b32 %r69, 0, %r68, %p17; + add.s32 %r70, %r69, %r67; + shfl.sync.up.b32 %r71|%p24, %r70, 8, 0, -1; + selp.b32 %r72, 0, %r71, %p16; + add.s32 %r73, %r72, %r70; + shfl.sync.up.b32 %r74|%p25, %r73, 16, 0, -1; + selp.b32 %r75, 0, %r74, %p15; + add.s32 %r16, %r75, %r73; + @%p20 bra $L__BB0_25; + st.shared.b32 [%r9], %r16; +$L__BB0_25: + setp.gt.u32 %p26, %r2, 31; bar.sync 0; - @%p25 bra $L__BB0_24; - setp.lt.u32 %p26, %r7, 16; - setp.lt.u32 %p27, %r7, 8; - setp.lt.u32 %p28, %r7, 4; - setp.lt.u32 %p29, %r7, 2; - setp.eq.b32 %p30, %r7, 0; - ld.shared.b32 %r71, [%r9]; - shfl.sync.up.b32 %r72|%p31, %r71, 1, 0, -1; - selp.b32 %r73, 0, %r72, %p30; - add.s32 %r74, %r73, %r71; - shfl.sync.up.b32 %r75|%p32, %r74, 2, 0, -1; - selp.b32 %r76, 0, %r75, %p29; - add.s32 %r77, %r76, %r74; - shfl.sync.up.b32 %r78|%p33, %r77, 4, 0, -1; - selp.b32 %r79, 0, %r78, %p28; - add.s32 %r80, %r79, %r77; - shfl.sync.up.b32 %r81|%p34, %r80, 8, 0, -1; - selp.b32 %r82, 0, %r81, %p27; - add.s32 %r83, %r82, %r80; - shfl.sync.up.b32 %r84|%p35, %r83, 16, 0, -1; - selp.b32 %r85, 0, %r84, %p26; - add.s32 %r86, %r85, %r83; - st.shared.b32 [%r9], %r86; -$L__BB0_24: - setp.lt.u32 %p36, %r2, 32; + @%p26 bra $L__BB0_27; + setp.lt.u32 %p27, %r8, 16; + setp.lt.u32 %p28, %r8, 8; + setp.lt.u32 %p29, %r8, 4; + setp.lt.u32 %p30, %r8, 2; + setp.eq.b32 %p31, %r8, 0; + ld.shared.b32 %r76, [%r10]; + shfl.sync.up.b32 %r77|%p32, %r76, 1, 0, -1; + selp.b32 %r78, 0, %r77, %p31; + add.s32 %r79, %r78, %r76; + shfl.sync.up.b32 %r80|%p33, %r79, 2, 0, -1; + selp.b32 %r81, 0, %r80, %p30; + add.s32 %r82, %r81, %r79; + shfl.sync.up.b32 %r83|%p34, %r82, 4, 0, -1; + selp.b32 %r84, 0, %r83, %p29; + add.s32 %r85, %r84, %r82; + shfl.sync.up.b32 %r86|%p35, %r85, 8, 0, -1; + selp.b32 %r87, 0, %r86, %p28; + add.s32 %r88, %r87, %r85; + shfl.sync.up.b32 %r89|%p36, %r88, 16, 0, -1; + selp.b32 %r90, 0, %r89, %p27; + add.s32 %r91, %r90, %r88; + st.shared.b32 [%r10], %r91; +$L__BB0_27: + setp.lt.u32 %p37, %r2, 32; bar.sync 0; - ld.shared.b32 %r16, [_ZZ18leleka_qsa_resolveE9warp_sums+124]; - sub.s32 %r17, %r15, %r14; - mov.b32 %r106, 0; - @%p36 bra $L__BB0_26; - ld.shared.b32 %r106, [%r8+-4]; -$L__BB0_26: - setp.ne.b32 %p37, %r2, 0; - add.s32 %r18, %r106, %r17; + ld.shared.b32 %r17, [_ZZ18leleka_qsa_resolveE9warp_sums+124]; + sub.s32 %r18, %r16, %r15; + mov.b32 %r110, 0; + @%p37 bra $L__BB0_29; + ld.shared.b32 %r110, [%r9+-4]; +$L__BB0_29: + setp.ne.b32 %p38, %r2, 0; + add.s32 %r19, %r110, %r18; bar.sync 0; - sub.s32 %r19, %r6, %r108; - @%p37 bra $L__BB0_28; + sub.s32 %r20, %r6, %r112; + @%p38 bra $L__BB0_31; st.shared.b32 [_ZZ18leleka_qsa_resolveE5s_cut], 1024; -$L__BB0_28: +$L__BB0_31: bar.sync 0; - add.s32 %r87, %r19, -1; - setp.ne.b32 %p38, %r18, %r87; - not.pred %p39, %p65; - or.pred %p40, %p39, %p38; - @%p40 bra $L__BB0_30; - st.shared.b32 [_ZZ18leleka_qsa_resolveE5s_cut], %r10; -$L__BB0_30: + add.s32 %r92, %r20, -1; + setp.ne.b32 %p39, %r19, %r92; + not.pred %p40, %p67; + or.pred %p41, %p40, %p39; + @%p41 bra $L__BB0_33; + st.shared.b32 [_ZZ18leleka_qsa_resolveE5s_cut], %r11; +$L__BB0_33: bar.sync 0; - ld.shared.s32 %rd16, [_ZZ18leleka_qsa_resolveE5s_cut]; - setp.ge.s32 %p41, %r18, %r19; - or.pred %p42, %p39, %p41; - @%p42 bra $L__BB0_32; - add.s32 %r89, %r18, %r108; - mul.wide.s32 %rd48, %r89, 4; + ld.shared.s32 %rd18, [_ZZ18leleka_qsa_resolveE5s_cut]; + setp.ge.s32 %p42, %r19, %r20; + or.pred %p43, %p40, %p42; + @%p43 bra $L__BB0_35; + add.s32 %r94, %r19, %r112; + mul.wide.s32 %rd48, %r94, 4; add.s64 %rd49, %rd4, %rd48; - st.global.b32 [%rd49], %r12; - st.global.b32 [%rd14], %r1; - bra.uni $L__BB0_34; -$L__BB0_32: - cvt.u32.u64 %r88, %rd16; - setp.eq.b32 %p43, %r13, %r1; - setp.ge.u32 %p44, %r2, %r88; - or.pred %p45, %p43, %p44; - @%p45 bra $L__BB0_34; - st.global.b32 [%rd15], 0; -$L__BB0_34: - min.s32 %r90, %r16, %r19; - add.s32 %r108, %r90, %r108; - add.s64 %rd50, %rd16, %rd12; - shr.u64 %rd51, %rd50, 51; - add.s64 %rd52, %rd50, %rd51; - shr.u64 %rd53, %rd52, 13; - cvt.u32.u64 %r91, %rd53; - mov.b64 %rd54, 8192; - cvt.u32.u64 %r92, %rd54; - mul.lo.s32 %r93, %r91, %r92; - cvt.u32.u64 %r94, %rd50; - sub.s32 %r107, %r94, %r93; - bar.sync 0; - add.s32 %r105, %r11, 1024; - setp.lt.s32 %p66, %r108, %r6; - setp.lt.u32 %p46, %r11, 23552; - and.pred %p47, %p66, %p46; - @%p47 bra $L__BB0_17; + st.global.b32 [%rd49], %r13; + st.global.b32 [%rd16], %r1; + bra.uni $L__BB0_37; $L__BB0_35: - min.s32 %r20, %r108, %r6; - setp.ge.s32 %p48, %r2, %r6; - @%p48 bra $L__BB0_62; - not.b32 %r95, %r2; - add.s32 %r21, %r6, %r95; - and.b32 %r96, %r21, 3072; - setp.eq.b32 %p49, %r96, 3072; - mov.b32 %r112, %r2; - @%p49 bra $L__BB0_43; - shr.u32 %r97, %r21, 10; - add.s32 %r98, %r97, 1; - and.b32 %r99, %r98, 3; - mul.wide.u32 %rd55, %r2, 4; - add.s64 %rd103, %rd4, %rd55; - add.s64 %rd102, %rd6, %rd55; - neg.s32 %r109, %r99; - shl.b32 %r100, %r98, 10; - and.b32 %r101, %r100, 3072; - or.b32 %r112, %r2, %r101; - mov.b32 %r110, %r2; -$L__BB0_38: - .pragma "nounroll"; - ld.global.b32 %r22, [%rd102]; - setp.le.s32 %p50, %r108, %r110; - mov.b32 %r111, -1; - @%p50 bra $L__BB0_42; - ld.global.b32 %r111, [%rd103]; - mul.wide.s32 %rd56, %r111, 4; - add.s64 %rd17, %rd3, %rd56; - ld.global.b32 %r23, [%rd17]; - setp.lt.s32 %p51, %r23, 0; - @%p51 bra $L__BB0_41; - mul.wide.u32 %rd57, %r23, 4; - add.s64 %rd58, %rd5, %rd57; - st.global.b32 [%rd58], -1; + cvt.u32.u64 %r93, %rd18; + setp.eq.b32 %p44, %r14, %r1; + setp.ge.u32 %p45, %r2, %r93; + or.pred %p46, %p44, %p45; + @%p46 bra $L__BB0_37; + st.global.b32 [%rd17], 0; +$L__BB0_37: + min.s32 %r95, %r17, %r20; + add.s32 %r112, %r95, %r112; + add.s64 %rd19, %rd18, %rd13; + and.b64 %rd50, %rd19, -4294967296; + setp.ne.b64 %p47, %rd50, 0; + @%p47 bra $L__BB0_39; + cvt.u32.u64 %r96, %rd12; + cvt.u32.u64 %r97, %rd19; + rem.u32 %r98, %r97, %r96; + cvt.u64.u32 %rd99, %r98; + bra.uni $L__BB0_40; +$L__BB0_39: + rem.s64 %rd99, %rd19, %rd12; +$L__BB0_40: + cvt.u32.u64 %r111, %rd99; + bar.sync 0; + add.s32 %r109, %r109, 1024; + setp.lt.s32 %p68, %r112, %r6; + setp.lt.s32 %p48, %r109, %r12; + and.pred %p49, %p68, %p48; + @%p49 bra $L__BB0_17; $L__BB0_41: - st.global.b32 [%rd17], %r22; - add.s64 %rd59, %rd2, %rd56; - st.global.b32 [%rd59], %r1; - add.s64 %rd60, %rd1, %rd56; - st.global.b32 [%rd60], 1; -$L__BB0_42: - mul.wide.s32 %rd61, %r22, 4; - add.s64 %rd62, %rd5, %rd61; - st.global.b32 [%rd62], %r111; - add.s32 %r110, %r110, 1024; - add.s64 %rd103, %rd103, 4096; - add.s64 %rd102, %rd102, 4096; - add.s32 %r109, %r109, 1; - setp.ne.b32 %p52, %r109, 0; - @%p52 bra $L__BB0_38; -$L__BB0_43: - setp.lt.u32 %p53, %r21, 3072; - @%p53 bra $L__BB0_62; - mul.wide.u32 %rd63, %r112, 4; - add.s64 %rd64, %rd63, 8192; - add.s64 %rd105, %rd6, %rd64; - add.s64 %rd104, %rd4, %rd64; -$L__BB0_45: - ld.global.b32 %r24, [%rd105+-8192]; - setp.le.s32 %p54, %r108, %r112; - mov.b32 %r113, -1; - @%p54 bra $L__BB0_49; - ld.global.b32 %r113, [%rd104+-8192]; - mul.wide.s32 %rd65, %r113, 4; - add.s64 %rd18, %rd3, %rd65; - ld.global.b32 %r25, [%rd18]; - setp.lt.s32 %p55, %r25, 0; - @%p55 bra $L__BB0_48; - mul.wide.u32 %rd66, %r25, 4; - add.s64 %rd67, %rd5, %rd66; - st.global.b32 [%rd67], -1; -$L__BB0_48: - st.global.b32 [%rd18], %r24; - add.s64 %rd68, %rd2, %rd65; - st.global.b32 [%rd68], %r1; - add.s64 %rd69, %rd1, %rd65; - st.global.b32 [%rd69], 1; -$L__BB0_49: - mul.wide.s32 %rd70, %r24, 4; - add.s64 %rd71, %rd5, %rd70; - st.global.b32 [%rd71], %r113; - ld.global.b32 %r26, [%rd105+-4096]; - add.s32 %r27, %r112, 1024; - setp.le.s32 %p56, %r108, %r27; - mov.b32 %r114, -1; - @%p56 bra $L__BB0_53; - ld.global.b32 %r114, [%rd104+-4096]; - mul.wide.s32 %rd72, %r114, 4; - add.s64 %rd19, %rd3, %rd72; - ld.global.b32 %r28, [%rd19]; - setp.lt.s32 %p57, %r28, 0; - @%p57 bra $L__BB0_52; - mul.wide.u32 %rd73, %r28, 4; - add.s64 %rd74, %rd5, %rd73; - st.global.b32 [%rd74], -1; -$L__BB0_52: - st.global.b32 [%rd19], %r26; - add.s64 %rd75, %rd2, %rd72; - st.global.b32 [%rd75], %r1; - add.s64 %rd76, %rd1, %rd72; - st.global.b32 [%rd76], 1; -$L__BB0_53: - mul.wide.s32 %rd77, %r26, 4; - add.s64 %rd78, %rd5, %rd77; - st.global.b32 [%rd78], %r114; - ld.global.b32 %r29, [%rd105]; - add.s32 %r30, %r27, 1024; - setp.le.s32 %p58, %r108, %r30; + min.s32 %r21, %r112, %r6; + setp.ge.s32 %p50, %r2, %r6; + @%p50 bra $L__BB0_68; + not.b32 %r99, %r2; + add.s32 %r22, %r6, %r99; + and.b32 %r100, %r22, 3072; + setp.eq.b32 %p51, %r100, 3072; + mov.b32 %r116, %r2; + @%p51 bra $L__BB0_49; + shr.u32 %r101, %r22, 10; + add.s32 %r102, %r101, 1; + and.b32 %r103, %r102, 3; + mul.wide.u32 %rd51, %r2, 4; + add.s64 %rd101, %rd4, %rd51; + add.s64 %rd100, %rd6, %rd51; + neg.s32 %r113, %r103; + shl.b32 %r104, %r102, 10; + and.b32 %r105, %r104, 3072; + or.b32 %r116, %r2, %r105; + mov.b32 %r114, %r2; +$L__BB0_44: + .pragma "nounroll"; + ld.global.b32 %r23, [%rd100]; + setp.le.s32 %p52, %r112, %r114; mov.b32 %r115, -1; - @%p58 bra $L__BB0_57; - ld.global.b32 %r115, [%rd104]; - mul.wide.s32 %rd79, %r115, 4; - add.s64 %rd20, %rd3, %rd79; - ld.global.b32 %r31, [%rd20]; - setp.lt.s32 %p59, %r31, 0; - @%p59 bra $L__BB0_56; - mul.wide.u32 %rd80, %r31, 4; - add.s64 %rd81, %rd5, %rd80; - st.global.b32 [%rd81], -1; -$L__BB0_56: - st.global.b32 [%rd20], %r29; - add.s64 %rd82, %rd2, %rd79; - st.global.b32 [%rd82], %r1; - add.s64 %rd83, %rd1, %rd79; - st.global.b32 [%rd83], 1; -$L__BB0_57: - mul.wide.s32 %rd84, %r29, 4; - add.s64 %rd85, %rd5, %rd84; - st.global.b32 [%rd85], %r115; - ld.global.b32 %r32, [%rd105+4096]; - add.s32 %r33, %r30, 1024; - setp.le.s32 %p60, %r108, %r33; - mov.b32 %r116, -1; - @%p60 bra $L__BB0_61; - ld.global.b32 %r116, [%rd104+4096]; - mul.wide.s32 %rd86, %r116, 4; - add.s64 %rd21, %rd3, %rd86; - ld.global.b32 %r34, [%rd21]; - setp.lt.s32 %p61, %r34, 0; - @%p61 bra $L__BB0_60; - mul.wide.u32 %rd87, %r34, 4; - add.s64 %rd88, %rd5, %rd87; - st.global.b32 [%rd88], -1; -$L__BB0_60: - st.global.b32 [%rd21], %r32; - add.s64 %rd89, %rd2, %rd86; - st.global.b32 [%rd89], %r1; - add.s64 %rd90, %rd1, %rd86; - st.global.b32 [%rd90], 1; -$L__BB0_61: - mul.wide.s32 %rd91, %r32, 4; - add.s64 %rd92, %rd5, %rd91; - st.global.b32 [%rd92], %r116; - add.s64 %rd105, %rd105, 16384; - add.s64 %rd104, %rd104, 16384; - add.s32 %r112, %r33, 1024; - setp.lt.s32 %p62, %r112, %r6; - @%p62 bra $L__BB0_45; + @%p52 bra $L__BB0_48; + ld.global.b32 %r115, [%rd101]; + mul.wide.s32 %rd52, %r115, 4; + add.s64 %rd20, %rd3, %rd52; + ld.global.b32 %r24, [%rd20]; + setp.lt.s32 %p53, %r24, 0; + @%p53 bra $L__BB0_47; + mul.wide.u32 %rd53, %r24, 4; + add.s64 %rd54, %rd5, %rd53; + st.global.b32 [%rd54], -1; +$L__BB0_47: + st.global.b32 [%rd20], %r23; + add.s64 %rd55, %rd2, %rd52; + st.global.b32 [%rd55], %r1; + add.s64 %rd56, %rd1, %rd52; + st.global.b32 [%rd56], 1; +$L__BB0_48: + mul.wide.s32 %rd57, %r23, 4; + add.s64 %rd58, %rd5, %rd57; + st.global.b32 [%rd58], %r115; + add.s32 %r114, %r114, 1024; + add.s64 %rd101, %rd101, 4096; + add.s64 %rd100, %rd100, 4096; + add.s32 %r113, %r113, 1; + setp.ne.b32 %p54, %r113, 0; + @%p54 bra $L__BB0_44; +$L__BB0_49: + setp.lt.u32 %p55, %r22, 3072; + @%p55 bra $L__BB0_68; + mul.wide.u32 %rd59, %r116, 4; + add.s64 %rd60, %rd59, 8192; + add.s64 %rd103, %rd6, %rd60; + add.s64 %rd102, %rd4, %rd60; +$L__BB0_51: + ld.global.b32 %r25, [%rd103+-8192]; + setp.le.s32 %p56, %r112, %r116; + mov.b32 %r117, -1; + @%p56 bra $L__BB0_55; + ld.global.b32 %r117, [%rd102+-8192]; + mul.wide.s32 %rd61, %r117, 4; + add.s64 %rd21, %rd3, %rd61; + ld.global.b32 %r26, [%rd21]; + setp.lt.s32 %p57, %r26, 0; + @%p57 bra $L__BB0_54; + mul.wide.u32 %rd62, %r26, 4; + add.s64 %rd63, %rd5, %rd62; + st.global.b32 [%rd63], -1; +$L__BB0_54: + st.global.b32 [%rd21], %r25; + add.s64 %rd64, %rd2, %rd61; + st.global.b32 [%rd64], %r1; + add.s64 %rd65, %rd1, %rd61; + st.global.b32 [%rd65], 1; +$L__BB0_55: + mul.wide.s32 %rd66, %r25, 4; + add.s64 %rd67, %rd5, %rd66; + st.global.b32 [%rd67], %r117; + ld.global.b32 %r27, [%rd103+-4096]; + add.s32 %r28, %r116, 1024; + setp.le.s32 %p58, %r112, %r28; + mov.b32 %r118, -1; + @%p58 bra $L__BB0_59; + ld.global.b32 %r118, [%rd102+-4096]; + mul.wide.s32 %rd68, %r118, 4; + add.s64 %rd22, %rd3, %rd68; + ld.global.b32 %r29, [%rd22]; + setp.lt.s32 %p59, %r29, 0; + @%p59 bra $L__BB0_58; + mul.wide.u32 %rd69, %r29, 4; + add.s64 %rd70, %rd5, %rd69; + st.global.b32 [%rd70], -1; +$L__BB0_58: + st.global.b32 [%rd22], %r27; + add.s64 %rd71, %rd2, %rd68; + st.global.b32 [%rd71], %r1; + add.s64 %rd72, %rd1, %rd68; + st.global.b32 [%rd72], 1; +$L__BB0_59: + mul.wide.s32 %rd73, %r27, 4; + add.s64 %rd74, %rd5, %rd73; + st.global.b32 [%rd74], %r118; + ld.global.b32 %r30, [%rd103]; + add.s32 %r31, %r28, 1024; + setp.le.s32 %p60, %r112, %r31; + mov.b32 %r119, -1; + @%p60 bra $L__BB0_63; + ld.global.b32 %r119, [%rd102]; + mul.wide.s32 %rd75, %r119, 4; + add.s64 %rd23, %rd3, %rd75; + ld.global.b32 %r32, [%rd23]; + setp.lt.s32 %p61, %r32, 0; + @%p61 bra $L__BB0_62; + mul.wide.u32 %rd76, %r32, 4; + add.s64 %rd77, %rd5, %rd76; + st.global.b32 [%rd77], -1; $L__BB0_62: - setp.ne.b32 %p63, %r2, 0; + st.global.b32 [%rd23], %r30; + add.s64 %rd78, %rd2, %rd75; + st.global.b32 [%rd78], %r1; + add.s64 %rd79, %rd1, %rd75; + st.global.b32 [%rd79], 1; +$L__BB0_63: + mul.wide.s32 %rd80, %r30, 4; + add.s64 %rd81, %rd5, %rd80; + st.global.b32 [%rd81], %r119; + ld.global.b32 %r33, [%rd103+4096]; + add.s32 %r34, %r31, 1024; + setp.le.s32 %p62, %r112, %r34; + mov.b32 %r120, -1; + @%p62 bra $L__BB0_67; + ld.global.b32 %r120, [%rd102+4096]; + mul.wide.s32 %rd82, %r120, 4; + add.s64 %rd24, %rd3, %rd82; + ld.global.b32 %r35, [%rd24]; + setp.lt.s32 %p63, %r35, 0; @%p63 bra $L__BB0_66; - st.global.b32 [%rd7], %r1; - st.global.b32 [%rd7+4], %r107; - st.global.b32 [%rd7+8], %r20; - not.pred %p64, %p66; - @%p64 bra $L__BB0_65; - st.global.b32 [%rd7+12], 1; -$L__BB0_65: - cvt.s64.s32 %rd93, %r20; - ld.global.b64 %rd94, [%rd7+16]; - add.s64 %rd95, %rd94, %rd93; - st.global.b64 [%rd7+16], %rd95; - ld.shared.s32 %rd96, [_ZZ18leleka_qsa_resolveE9s_lookups]; - ld.global.b64 %rd97, [%rd7+24]; - add.s64 %rd98, %rd97, %rd96; - st.global.b64 [%rd7+24], %rd98; - ld.global.b64 %rd99, [%rd7+32]; - add.s64 %rd100, %rd99, 1; - st.global.b64 [%rd7+32], %rd100; + mul.wide.u32 %rd83, %r35, 4; + add.s64 %rd84, %rd5, %rd83; + st.global.b32 [%rd84], -1; $L__BB0_66: + st.global.b32 [%rd24], %r33; + add.s64 %rd85, %rd2, %rd82; + st.global.b32 [%rd85], %r1; + add.s64 %rd86, %rd1, %rd82; + st.global.b32 [%rd86], 1; +$L__BB0_67: + mul.wide.s32 %rd87, %r33, 4; + add.s64 %rd88, %rd5, %rd87; + st.global.b32 [%rd88], %r120; + add.s64 %rd103, %rd103, 16384; + add.s64 %rd102, %rd102, 16384; + add.s32 %r116, %r34, 1024; + setp.lt.s32 %p64, %r116, %r6; + @%p64 bra $L__BB0_51; +$L__BB0_68: + setp.ne.b32 %p65, %r2, 0; + @%p65 bra $L__BB0_72; + st.global.b32 [%rd7], %r1; + st.global.b32 [%rd7+4], %r111; + st.global.b32 [%rd7+8], %r21; + not.pred %p66, %p68; + @%p66 bra $L__BB0_71; + st.global.b32 [%rd7+12], 1; +$L__BB0_71: + cvt.s64.s32 %rd89, %r21; + ld.global.b64 %rd90, [%rd7+16]; + add.s64 %rd91, %rd90, %rd89; + st.global.b64 [%rd7+16], %rd91; + ld.shared.s32 %rd92, [_ZZ18leleka_qsa_resolveE9s_lookups]; + ld.global.b64 %rd93, [%rd7+24]; + add.s64 %rd94, %rd93, %rd92; + st.global.b64 [%rd7+24], %rd94; + ld.global.b64 %rd95, [%rd7+32]; + add.s64 %rd96, %rd95, 1; + st.global.b64 [%rd7+32], %rd96; +$L__BB0_72: ret; } @@ -610,196 +625,185 @@ $L__BB1_15: .param .u64 .ptr .align 1 leleka_qsa_stream_reset_param_4, .param .u64 .ptr .align 1 leleka_qsa_stream_reset_param_5, .param .u64 .ptr .align 1 leleka_qsa_stream_reset_param_6, - .param .u64 leleka_qsa_stream_reset_param_7 + .param .u64 leleka_qsa_stream_reset_param_7, + .param .u64 leleka_qsa_stream_reset_param_8 ) { .reg .pred %p<16>; .reg .b32 %r<11>; - .reg .b64 %rd<96>; + .reg .b64 %rd<85>; - ld.param.b64 %rd31, [leleka_qsa_stream_reset_param_0]; - ld.param.b64 %rd32, [leleka_qsa_stream_reset_param_1]; - ld.param.b64 %rd33, [leleka_qsa_stream_reset_param_2]; - ld.param.b64 %rd34, [leleka_qsa_stream_reset_param_3]; - ld.param.b64 %rd29, [leleka_qsa_stream_reset_param_4]; - ld.param.b64 %rd30, [leleka_qsa_stream_reset_param_7]; - cvta.to.global.u64 %rd1, %rd31; - cvta.to.global.u64 %rd2, %rd34; - cvta.to.global.u64 %rd3, %rd33; - cvta.to.global.u64 %rd4, %rd32; + ld.param.b64 %rd22, [leleka_qsa_stream_reset_param_0]; + ld.param.b64 %rd23, [leleka_qsa_stream_reset_param_1]; + ld.param.b64 %rd24, [leleka_qsa_stream_reset_param_2]; + ld.param.b64 %rd25, [leleka_qsa_stream_reset_param_3]; + ld.param.b64 %rd19, [leleka_qsa_stream_reset_param_4]; + ld.param.b64 %rd20, [leleka_qsa_stream_reset_param_7]; + ld.param.b64 %rd21, [leleka_qsa_stream_reset_param_8]; + cvta.to.global.u64 %rd1, %rd22; + cvta.to.global.u64 %rd2, %rd25; + cvta.to.global.u64 %rd3, %rd24; + cvta.to.global.u64 %rd4, %rd23; mov.u32 %r1, %ctaid.x; cvt.u64.u32 %rd5, %r1; mov.u32 %r2, %ntid.x; cvt.u64.u32 %rd6, %r2; - mul.wide.u32 %rd35, %r1, %r2; + mul.wide.u32 %rd26, %r1, %r2; mov.u32 %r3, %tid.x; cvt.u64.u32 %rd7, %r3; - add.s64 %rd8, %rd35, %rd7; + add.s64 %rd8, %rd26, %rd7; mov.u32 %r4, %nctaid.x; cvt.u64.u32 %rd9, %r4; mul.wide.u32 %rd10, %r4, %r2; - setp.ge.s64 %p1, %rd8, %rd30; + setp.ge.s64 %p1, %rd8, %rd20; @%p1 bra $L__BB2_10; - add.s64 %rd36, %rd9, %rd5; - mad.lo.s64 %rd37, %rd36, %rd6, %rd7; - max.u64 %rd38, %rd30, %rd37; - setp.lt.u64 %p2, %rd37, %rd30; + add.s64 %rd27, %rd9, %rd5; + mad.lo.s64 %rd28, %rd27, %rd6, %rd7; + max.u64 %rd29, %rd20, %rd28; + setp.lt.u64 %p2, %rd28, %rd20; selp.b64 %rd11, 1, 0, %p2; - add.s64 %rd39, %rd37, %rd11; - sub.s64 %rd12, %rd38, %rd39; - or.b64 %rd40, %rd12, %rd10; - and.b64 %rd41, %rd40, -4294967296; - setp.ne.b64 %p3, %rd41, 0; + add.s64 %rd30, %rd28, %rd11; + sub.s64 %rd12, %rd29, %rd30; + or.b64 %rd31, %rd12, %rd10; + and.b64 %rd32, %rd31, -4294967296; + setp.ne.b64 %p3, %rd32, 0; @%p3 bra $L__BB2_3; cvt.u32.u64 %r5, %rd10; cvt.u32.u64 %r6, %rd12; div.u32 %r7, %r6, %r5; - cvt.u64.u32 %rd87, %r7; + cvt.u64.u32 %rd77, %r7; bra.uni $L__BB2_4; $L__BB2_3: - div.u64 %rd87, %rd12, %rd10; + div.u64 %rd77, %rd12, %rd10; $L__BB2_4: - add.s64 %rd13, %rd87, %rd11; - and.b64 %rd42, %rd13, 3; - setp.eq.b64 %p4, %rd42, 3; - mov.b64 %rd90, %rd8; + add.s64 %rd13, %rd77, %rd11; + and.b64 %rd33, %rd13, 3; + setp.eq.b64 %p4, %rd33, 3; + mov.b64 %rd80, %rd8; @%p4 bra $L__BB2_7; - shl.b64 %rd43, %rd8, 2; - add.s64 %rd89, %rd1, %rd43; + shl.b64 %rd34, %rd8, 2; + add.s64 %rd79, %rd1, %rd34; shl.b64 %rd14, %rd10, 2; - add.s64 %rd44, %rd13, 1; - and.b64 %rd45, %rd44, 3; - neg.s64 %rd88, %rd45; - mov.b64 %rd90, %rd8; + add.s64 %rd35, %rd13, 1; + and.b64 %rd36, %rd35, 3; + neg.s64 %rd78, %rd36; + mov.b64 %rd80, %rd8; $L__BB2_6: .pragma "nounroll"; - st.global.b32 [%rd89], -1; - add.s64 %rd90, %rd90, %rd10; - add.s64 %rd89, %rd89, %rd14; - add.s64 %rd88, %rd88, 1; - setp.ne.b64 %p5, %rd88, 0; + st.global.b32 [%rd79], -1; + add.s64 %rd80, %rd80, %rd10; + add.s64 %rd79, %rd79, %rd14; + add.s64 %rd78, %rd78, 1; + setp.ne.b64 %p5, %rd78, 0; @%p5 bra $L__BB2_6; $L__BB2_7: setp.lt.u64 %p6, %rd13, 3; @%p6 bra $L__BB2_10; - shl.b64 %rd49, %rd10, 2; + shl.b64 %rd40, %rd10, 2; $L__BB2_9: - shl.b64 %rd46, %rd90, 2; - add.s64 %rd47, %rd1, %rd46; - st.global.b32 [%rd47], -1; - add.s64 %rd48, %rd90, %rd10; - add.s64 %rd50, %rd47, %rd49; - st.global.b32 [%rd50], -1; - add.s64 %rd51, %rd48, %rd10; - add.s64 %rd52, %rd50, %rd49; - st.global.b32 [%rd52], -1; - add.s64 %rd53, %rd51, %rd10; - add.s64 %rd54, %rd52, %rd49; - st.global.b32 [%rd54], -1; - add.s64 %rd90, %rd53, %rd10; - setp.lt.s64 %p7, %rd90, %rd30; + shl.b64 %rd37, %rd80, 2; + add.s64 %rd38, %rd1, %rd37; + st.global.b32 [%rd38], -1; + add.s64 %rd39, %rd80, %rd10; + add.s64 %rd41, %rd38, %rd40; + st.global.b32 [%rd41], -1; + add.s64 %rd42, %rd39, %rd10; + add.s64 %rd43, %rd41, %rd40; + st.global.b32 [%rd43], -1; + add.s64 %rd44, %rd42, %rd10; + add.s64 %rd45, %rd43, %rd40; + st.global.b32 [%rd45], -1; + add.s64 %rd80, %rd44, %rd10; + setp.lt.s64 %p7, %rd80, %rd20; @%p7 bra $L__BB2_9; $L__BB2_10: - setp.gt.u64 %p8, %rd8, 8191; + setp.ge.s64 %p8, %rd8, %rd21; @%p8 bra $L__BB2_20; - add.s64 %rd55, %rd8, %rd10; - max.u64 %rd56, %rd55, 8192; - setp.lt.u64 %p9, %rd55, 8192; + add.s64 %rd46, %rd8, %rd10; + max.u64 %rd47, %rd21, %rd46; + setp.lt.u64 %p9, %rd46, %rd21; selp.b64 %rd15, 1, 0, %p9; - add.s64 %rd57, %rd55, %rd15; - sub.s64 %rd16, %rd56, %rd57; - or.b64 %rd58, %rd16, %rd10; - and.b64 %rd59, %rd58, -4294967296; - setp.ne.b64 %p10, %rd59, 0; + add.s64 %rd48, %rd46, %rd15; + sub.s64 %rd16, %rd47, %rd48; + or.b64 %rd49, %rd16, %rd10; + and.b64 %rd50, %rd49, -4294967296; + setp.ne.b64 %p10, %rd50, 0; @%p10 bra $L__BB2_13; cvt.u32.u64 %r8, %rd10; cvt.u32.u64 %r9, %rd16; div.u32 %r10, %r9, %r8; - cvt.u64.u32 %rd91, %r10; + cvt.u64.u32 %rd81, %r10; bra.uni $L__BB2_14; $L__BB2_13: - div.u64 %rd91, %rd16, %rd10; + div.u64 %rd81, %rd16, %rd10; $L__BB2_14: - add.s64 %rd17, %rd91, %rd15; - and.b64 %rd60, %rd17, 3; - setp.eq.b64 %p11, %rd60, 3; - mov.b64 %rd94, %rd8; + add.s64 %rd17, %rd81, %rd15; + and.b64 %rd51, %rd17, 3; + setp.eq.b64 %p11, %rd51, 3; + mov.b64 %rd84, %rd8; @%p11 bra $L__BB2_17; - shl.b64 %rd93, %rd8, 2; + shl.b64 %rd83, %rd8, 2; shl.b64 %rd18, %rd10, 2; - add.s64 %rd61, %rd17, 1; - and.b64 %rd62, %rd61, 3; - neg.s64 %rd92, %rd62; - mov.b64 %rd94, %rd8; + add.s64 %rd52, %rd17, 1; + and.b64 %rd53, %rd52, 3; + neg.s64 %rd82, %rd53; + mov.b64 %rd84, %rd8; $L__BB2_16: .pragma "nounroll"; - add.s64 %rd63, %rd4, %rd93; - st.global.b32 [%rd63], -1; - add.s64 %rd64, %rd3, %rd93; - st.global.b32 [%rd64], -1; - add.s64 %rd65, %rd2, %rd93; - st.global.b32 [%rd65], 0; - add.s64 %rd94, %rd94, %rd10; - add.s64 %rd93, %rd93, %rd18; - add.s64 %rd92, %rd92, 1; - setp.ne.b64 %p12, %rd92, 0; + add.s64 %rd54, %rd4, %rd83; + st.global.b32 [%rd54], -1; + add.s64 %rd55, %rd3, %rd83; + st.global.b32 [%rd55], -1; + add.s64 %rd56, %rd2, %rd83; + st.global.b32 [%rd56], 0; + add.s64 %rd84, %rd84, %rd10; + add.s64 %rd83, %rd83, %rd18; + add.s64 %rd82, %rd82, 1; + setp.ne.b64 %p12, %rd82, 0; @%p12 bra $L__BB2_16; $L__BB2_17: setp.lt.u64 %p13, %rd17, 3; @%p13 bra $L__BB2_20; - shl.b64 %rd66, %rd10, 2; - add.s64 %rd19, %rd2, %rd66; - shl.b64 %rd95, %rd94, 2; - shl.b64 %rd20, %rd10, 4; - shl.b64 %rd67, %rd10, 3; - add.s64 %rd21, %rd2, %rd67; - mul.lo.s64 %rd68, %rd10, 12; - add.s64 %rd22, %rd2, %rd68; - add.s64 %rd23, %rd3, %rd66; - add.s64 %rd24, %rd3, %rd67; - add.s64 %rd25, %rd3, %rd68; - add.s64 %rd26, %rd4, %rd66; - add.s64 %rd27, %rd4, %rd67; - add.s64 %rd28, %rd4, %rd68; + shl.b64 %rd62, %rd10, 2; $L__BB2_19: - add.s64 %rd69, %rd4, %rd95; - st.global.b32 [%rd69], -1; - add.s64 %rd70, %rd3, %rd95; - st.global.b32 [%rd70], -1; - add.s64 %rd71, %rd2, %rd95; - st.global.b32 [%rd71], 0; - add.s64 %rd72, %rd94, %rd10; - add.s64 %rd73, %rd26, %rd95; - st.global.b32 [%rd73], -1; - add.s64 %rd74, %rd23, %rd95; - st.global.b32 [%rd74], -1; - add.s64 %rd75, %rd19, %rd95; - st.global.b32 [%rd75], 0; - add.s64 %rd76, %rd72, %rd10; - add.s64 %rd77, %rd27, %rd95; - st.global.b32 [%rd77], -1; - add.s64 %rd78, %rd24, %rd95; - st.global.b32 [%rd78], -1; - add.s64 %rd79, %rd21, %rd95; - st.global.b32 [%rd79], 0; - add.s64 %rd80, %rd76, %rd10; - add.s64 %rd81, %rd28, %rd95; - st.global.b32 [%rd81], -1; - add.s64 %rd82, %rd25, %rd95; - st.global.b32 [%rd82], -1; - add.s64 %rd83, %rd22, %rd95; - st.global.b32 [%rd83], 0; - add.s64 %rd94, %rd80, %rd10; - add.s64 %rd95, %rd95, %rd20; - setp.lt.u64 %p14, %rd94, 8192; + shl.b64 %rd57, %rd84, 2; + add.s64 %rd58, %rd4, %rd57; + st.global.b32 [%rd58], -1; + add.s64 %rd59, %rd3, %rd57; + st.global.b32 [%rd59], -1; + add.s64 %rd60, %rd2, %rd57; + st.global.b32 [%rd60], 0; + add.s64 %rd61, %rd84, %rd10; + add.s64 %rd63, %rd58, %rd62; + st.global.b32 [%rd63], -1; + add.s64 %rd64, %rd59, %rd62; + st.global.b32 [%rd64], -1; + add.s64 %rd65, %rd60, %rd62; + st.global.b32 [%rd65], 0; + add.s64 %rd66, %rd61, %rd10; + add.s64 %rd67, %rd63, %rd62; + st.global.b32 [%rd67], -1; + add.s64 %rd68, %rd64, %rd62; + st.global.b32 [%rd68], -1; + add.s64 %rd69, %rd65, %rd62; + st.global.b32 [%rd69], 0; + add.s64 %rd70, %rd66, %rd10; + add.s64 %rd71, %rd67, %rd62; + st.global.b32 [%rd71], -1; + add.s64 %rd72, %rd68, %rd62; + st.global.b32 [%rd72], -1; + add.s64 %rd73, %rd69, %rd62; + st.global.b32 [%rd73], 0; + add.s64 %rd84, %rd70, %rd10; + setp.lt.s64 %p14, %rd84, %rd21; @%p14 bra $L__BB2_19; $L__BB2_20: setp.gt.u64 %p15, %rd8, 15; @%p15 bra $L__BB2_22; - cvta.to.global.u64 %rd84, %rd29; - shl.b64 %rd85, %rd8, 2; - add.s64 %rd86, %rd84, %rd85; - st.global.b32 [%rd86], 0; + cvta.to.global.u64 %rd74, %rd19; + shl.b64 %rd75, %rd8, 2; + add.s64 %rd76, %rd74, %rd75; + st.global.b32 [%rd76], 0; $L__BB2_22: ret; diff --git a/crates/cuda-driver/src/sm86_table.rs b/crates/cuda-driver/src/sm86_table.rs index bccc827a..2ff3156c 100644 --- a/crates/cuda-driver/src/sm86_table.rs +++ b/crates/cuda-driver/src/sm86_table.rs @@ -440,13 +440,6 @@ pub(crate) static COMPANIONS: &[Companion] = &[ sha: [0x36, 0x1d, 0xb3, 0xe8, 0x47, 0x1e, 0x42, 0x77, 0x8a, 0x4b, 0x7d, 0x45, 0x9a, 0xf7, 0x28, 0x9a, 0xa8, 0xe8, 0x01, 0x7b, 0xb3, 0xa7, 0x45, 0x5e, 0x6a, 0xa2, 0xe0, 0x49, 0xb2, 0x2a, 0xd0, 0x93], ptx: concat!(include_str!("../ptx-sm86/experimental_kv_q4.ptx"), "\0").as_bytes(), }, - Companion { - name: "qsa_prompt_resolver.ptx", - key: [0x74, 0x8a, 0x2e, 0x0d, 0x5f, 0xcd, 0x12, 0xa9, 0xd4, 0x9a, 0x20, 0xfa, 0x15, 0x56, 0x19, 0x0b, 0x22, 0xb0, 0x63, 0x06, 0x80, 0xc7, 0xa4, 0xef, 0x39, 0x8d, 0x90, 0x1f, 0x47, 0xf4, 0x71, 0xb3], - len: 23782, - sha: [0x24, 0x47, 0x16, 0x72, 0x93, 0x97, 0x33, 0x83, 0xcb, 0x42, 0xaf, 0xd7, 0x3f, 0xc2, 0x80, 0xb1, 0x4f, 0x67, 0x9b, 0xae, 0x30, 0xad, 0x84, 0x76, 0x4e, 0xd7, 0x4b, 0xd0, 0x7d, 0x2a, 0x6c, 0xa8], - ptx: concat!(include_str!("../ptx-sm86/qsa_prompt_resolver.ptx"), "\0").as_bytes(), - }, Companion { name: "qwen_qsa_attention_native.ptx", key: [0x77, 0x72, 0xe4, 0xe7, 0x5d, 0x78, 0xa9, 0x91, 0x01, 0x44, 0xca, 0x10, 0x85, 0x51, 0x80, 0x0f, 0xd4, 0x29, 0x69, 0x55, 0x78, 0x15, 0x40, 0xaf, 0xb6, 0x5f, 0x53, 0xd6, 0x12, 0xd7, 0xe1, 0xf3], @@ -545,6 +538,13 @@ pub(crate) static COMPANIONS: &[Companion] = &[ sha: [0x51, 0x62, 0x2e, 0x4f, 0x08, 0xa7, 0xe1, 0xfb, 0x52, 0x0f, 0xac, 0x0d, 0x0d, 0x8d, 0x2c, 0x3b, 0x61, 0xdc, 0xa1, 0x22, 0x70, 0x51, 0xaa, 0x14, 0xf6, 0xf7, 0x7d, 0xfc, 0x0a, 0xdf, 0x57, 0xad], ptx: concat!(include_str!("../ptx-sm86/qsa_prompt_indexer.ptx"), "\0").as_bytes(), }, + Companion { + name: "qsa_prompt_resolver.ptx", + key: [0x8d, 0x3e, 0xcb, 0xae, 0xcb, 0xf2, 0x84, 0x45, 0xba, 0x64, 0x48, 0x5b, 0xdf, 0xf3, 0xd9, 0x1a, 0x21, 0xd8, 0x7b, 0x85, 0xd5, 0x93, 0x9a, 0x01, 0x52, 0xef, 0x2f, 0x24, 0x14, 0x48, 0x0e, 0x22], + len: 23915, + sha: [0x32, 0xd9, 0x6c, 0xa6, 0xa7, 0x2f, 0x40, 0xed, 0xa2, 0x1d, 0x51, 0xd9, 0xf4, 0xd4, 0xd3, 0x77, 0xc3, 0x73, 0xc6, 0x37, 0x83, 0xcc, 0x42, 0x29, 0x10, 0x88, 0x3b, 0xb8, 0xd8, 0xd8, 0xb0, 0x8d], + ptx: concat!(include_str!("../ptx-sm86/qsa_prompt_resolver.ptx"), "\0").as_bytes(), + }, Companion { name: "q2_0_q8_1.ptx", key: [0x8e, 0x81, 0xdb, 0xba, 0xa7, 0x6d, 0x85, 0x16, 0x47, 0x63, 0x39, 0xc1, 0x68, 0xf1, 0xd9, 0xc1, 0x72, 0x34, 0x1a, 0x78, 0xcc, 0xec, 0xda, 0x08, 0x71, 0x4a, 0x13, 0xa5, 0x68, 0x7e, 0x3b, 0x6e], From 6c208972baa8d90d6daddd2b51f1e8c3f78e61ae Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 11:27:08 +0200 Subject: [PATCH 2/8] feat(experts): low-RAM mapped expert source (the Original's --mmap-experts, GGUF in place) The serve stack's routed experts came only from `load_resident_expert_source`, a 50 GB RAM copy of the 144 shard-0 banks that `MappedExpertBank` then page-locks whole: impossible on a 32-48 GB PC. * model-format: `ResidentTensor` storage is an owned copy or a read-only MAP_SHARED mapping of the verified shard (`VerifiedGgufFile::map_resident_tensor`, same descriptor, bounds and size checks); `Qwen4ExpArtifact::load_mapped_expert_source` builds the same bank catalog from mappings, no RAM admission (generate.cpp `src.set_gguf` + `FileExpertSource::open`). The crate's lint is relaxed from forbid to deny so exactly this mapping owner can allow its mmap/munmap/slice. * cuda-driver: a lease of mapped banks makes `MappedExpertBank` pageable: no cuMemHostRegister; every consumer the Original serve stack uses (`cache_source` for the prompt copy ring, VRAM tier fills/swaps, PCIe staging) copies with cuMemcpyHtoDAsync from pageable memory; the zero-copy device aliases (`retained_span_handle`, `copy_triplet`) are refused. * runtime: `ModelBinding::load_mapped_expert_source`. The bytes are the file's, so consumers see what the resident copy holds. Unit test `mapped_tensor_is_the_files_bytes_and_a_retained_owner`; model-format --lib 128 passed. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/cuda-driver/src/mapped_expert_bank.rs | 41 +++- .../qwen4exp_resident_expert_source.rs | 21 ++ crates/model-format/Cargo.toml | 13 +- crates/model-format/src/gguf_resident.rs | 200 +++++++++++++++++- .../src/qwen4exp_digest_capture.rs | 1 + .../src/qwen4exp_expert_source_bank.rs | 91 ++++++++ 7 files changed, 356 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3f497d00..5e85acdf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1036,6 +1036,7 @@ dependencies = [ name = "leleka-model-format" version = "0.1.0" dependencies = [ + "rustix", "sha2", ] diff --git a/crates/cuda-driver/src/mapped_expert_bank.rs b/crates/cuda-driver/src/mapped_expert_bank.rs index a93a838c..0386cca3 100644 --- a/crates/cuda-driver/src/mapped_expert_bank.rs +++ b/crates/cuda-driver/src/mapped_expert_bank.rs @@ -21,6 +21,13 @@ pub struct MappedExpertBank<'ctx> { api: Option, page_charge: usize, closed: bool, + /// The low-RAM source: the banks are read-only shared mappings of the GGUF file + /// (`ResidentExpertBankLease::file_mapped`). They are NOT page-locked (that would read and lock the whole + /// 50 GB file in RAM); every consumer copies from pageable memory (`cache_source` + `cuMemcpyHtoDAsync`, + /// which the driver stages), and the zero-copy device aliases (`retained_span_handle`, `copy_triplet`) + /// are refused. This is the Original's `--mmap-experts` without `--resident-cpu-experts`: unpinned + /// experts are copied, the OS file cache keeps the hot ones. + pageable: bool, } impl Context<'_> { pub fn mapped_expert_bank<'ctx>( @@ -32,6 +39,10 @@ impl Context<'_> { return Err(Error::InvalidSize); } let page = api::page_size()?; + let pageable = lease.file_mapped(); + if members.iter().any(|m| m.file_mapped() != pageable) { + return Err(Error::InvalidSize); + } let mut ranges = Vec::new(); ranges .try_reserve_exact(BANKS) @@ -110,10 +121,14 @@ impl Context<'_> { api: None, page_charge: extra, closed: false, + pageable, }; let guard = self.enter()?; let operation = (|| { owner.api = Some(api::MappedApi::load()?); + if owner.pageable { + return Ok(()); + } for bank in &mut owner.banks { owner .api @@ -146,7 +161,7 @@ impl<'ctx> MappedExpertBank<'ctx> { /// Validate the retained registered owner before the literal queued H2D /// cache fill. The device alias is deliberately not exported to runtime. pub(crate) fn cache_source(&self, span: &ResidentExpertBankSpan) -> Result<&[u8]> { - self.alias(span)?; + self.check(span)?; let layer = match span.role() { TensorRole::Layer { layer, .. } => layer, _ => return Err(Error::InvalidSize), @@ -189,7 +204,23 @@ impl<'ctx> MappedExpertBank<'ctx> { + 2 * size_of::() + self.banks.capacity() * size_of::() } + /// True for the low-RAM source: pageable file-mapped banks, no device aliases (see the field). + pub fn pageable(&self) -> bool { + self.pageable + } + /// The device alias of a registered span: refused for pageable banks. fn alias(&self, span: &ResidentExpertBankSpan) -> Result { + let n = self.check(span)?; + if self.pageable { + return Err(Error::UnsupportedQwenOperation); + } + self.banks[n] + .alias + .checked_add(span.offset() as u64) + .ok_or(Error::InvalidSize) + } + /// Every check of a span against its retained bank except the device alias; returns the bank index. + fn check(&self, span: &ResidentExpertBankSpan) -> Result { if self.closed || self.context.is_poisoned() { return Err(Error::ContextPoisoned); } @@ -206,7 +237,7 @@ impl<'ctx> MappedExpertBank<'ctx> { _ => return Err(Error::InvalidSize), }; let bank = &self.banks[n]; - if !bank.registered + if (!bank.registered && !self.pageable) || !span.belongs_to(&bank.member) || span.bytes().is_empty() || span @@ -218,9 +249,7 @@ impl<'ctx> MappedExpertBank<'ctx> { { return Err(Error::InvalidSize); } - bank.alias - .checked_add(span.offset() as u64) - .ok_or(Error::InvalidSize) + Ok(n) } pub fn eligible(&self, spans: &[ResidentExpertBankSpan; 3]) -> bool { let layer = match spans[0].role() { @@ -235,7 +264,7 @@ impl<'ctx> MappedExpertBank<'ctx> { }; span.role() == TensorRole::Layer { layer, role } && span.expert() == spans[0].expert() - && self.alias(span).is_ok() + && self.check(span).is_ok() }) } pub fn copy_triplet( diff --git a/crates/leleka-runtime/src/model_binding/qwen4exp_resident_expert_source.rs b/crates/leleka-runtime/src/model_binding/qwen4exp_resident_expert_source.rs index 57c08b88..bb078b7e 100644 --- a/crates/leleka-runtime/src/model_binding/qwen4exp_resident_expert_source.rs +++ b/crates/leleka-runtime/src/model_binding/qwen4exp_resident_expert_source.rs @@ -25,6 +25,27 @@ impl ModelBinding { ResidentExpertSourceError::Read(_) => InputBindingError::Read, }) } + /// The low-RAM form of `load_resident_expert_source`: the same banks as read-only shared mappings of shard 0 + /// (the Original's `--mmap-experts`, GGUF in place). Same preconditions; no RAM is committed for the experts. + #[cfg(target_os = "linux")] + pub(crate) fn load_mapped_expert_source( + &mut self, + ) -> InputResult { + if self.kar_ple.is_none() || self.mtp.is_none() { + return Err(InputBindingError::Metadata); + } + self.mtp_weights()?; + self.artifact + .get_mut() + .load_mapped_expert_source() + .map_err(|error| match error { + ResidentExpertSourceError::Geometry => InputBindingError::Geometry, + ResidentExpertSourceError::AlreadyEnabled => InputBindingError::Metadata, + ResidentExpertSourceError::Allocation + | ResidentExpertSourceError::MemoryAdmission => InputBindingError::Allocation, + ResidentExpertSourceError::Read(_) => InputBindingError::Read, + }) + } pub(crate) fn resident_expert_source_report( &self, ) -> InputResult> { diff --git a/crates/model-format/Cargo.toml b/crates/model-format/Cargo.toml index b729f534..71200454 100644 --- a/crates/model-format/Cargo.toml +++ b/crates/model-format/Cargo.toml @@ -10,5 +10,14 @@ autotests = false [dependencies] sha2 = "0.11" -[lints] -workspace = true +[target.'cfg(target_os = "linux")'.dependencies] +rustix = { version = "=1.1.5", features = ["mm", "param"] } + +# The workspace forbids unsafe code; this crate denies it instead so that exactly one owner, the read-only +# shared mapping of a verified GGUF tensor (gguf_resident.rs `FileSpan`, the low-RAM expert source), can +# `#[allow]` its mmap/munmap/slice. Everything else stays unsafe-free. +[lints.rust] +unsafe_code = "deny" + +[lints.clippy] +all = "warn" diff --git a/crates/model-format/src/gguf_resident.rs b/crates/model-format/src/gguf_resident.rs index 844015c6..23f2e4f9 100644 --- a/crates/model-format/src/gguf_resident.rs +++ b/crates/model-format/src/gguf_resident.rs @@ -28,7 +28,7 @@ fn next_source_id() -> Result { pub(crate) struct ResidentTensor { source: u64, tensor_number: usize, - bytes: Box<[u8]>, + bytes: ResidentStorage, charged_bytes: usize, } impl ResidentTensor { @@ -38,6 +38,64 @@ impl ResidentTensor { pub(crate) fn len(&self) -> usize { self.bytes.len() } + /// True when the bytes are the verified file's own pages (the Original's `--mmap-experts` GGUF-in-place + /// source), false for an owned RAM copy. + pub(crate) fn file_mapped(&self) -> bool { + matches!(self.bytes, ResidentStorage::Mapped(_)) + } +} + +/// Where a retained tensor's bytes live: an owned copy in RAM (the resident source), or a read-only shared +/// mapping of the verified GGUF file itself (the low-RAM source: the OS file cache holds what is used and +/// can give it back; the bytes are the file's, so the answers are the same). +enum ResidentStorage { + Owned(Box<[u8]>), + Mapped(FileSpan), +} +impl ResidentStorage { + fn as_slice(&self) -> &[u8] { + match self { + Self::Owned(bytes) => bytes, + Self::Mapped(span) => span.as_slice(), + } + } + fn len(&self) -> usize { + self.as_slice().len() + } +} +impl std::ops::Deref for ResidentStorage { + type Target = [u8]; + fn deref(&self) -> &[u8] { + self.as_slice() + } +} + +/// A `PROT_READ`/`MAP_SHARED` mapping of one tensor's exact byte range of a verified file (rounded out to +/// pages for the kernel, never exposed beyond the tensor). Unmapped on drop. +pub(crate) struct FileSpan { + base: *mut std::ffi::c_void, + map_len: usize, + start: usize, + len: usize, +} +impl FileSpan { + #[allow(unsafe_code)] + fn as_slice(&self) -> &[u8] { + // SAFETY: `base..base+map_len` is a live read-only mapping owned by `self`; `start + len <= map_len` + // was checked at construction. The source file's stability is the `VerifiedGgufFile` contract (its + // contents must not change while the handle and anything retained from it are alive). + unsafe { std::slice::from_raw_parts(self.base.cast::().add(self.start), self.len) } + } +} +impl Drop for FileSpan { + #[allow(unsafe_code)] + fn drop(&mut self) { + #[cfg(target_os = "linux")] + // SAFETY: exact base/length returned by mmap; no borrow of the slice outlives `self`. + unsafe { + let _ = rustix::mm::munmap(self.base, self.map_len); + } + } } impl VerifiedGgufFile { /// Constructor is source-owned: arbitrary caller bytes cannot become a bank. @@ -84,10 +142,83 @@ impl VerifiedGgufFile { Ok(ResidentTensor { source, tensor_number, - bytes, + bytes: ResidentStorage::Owned(bytes), charged_bytes, }) } + /// The Original's `--mmap-experts` with the GGUF in place (`FileExpertSource::set_gguf`): the tensor's + /// bytes are a read-only shared mapping of this verified file instead of a copy, so no RAM is committed + /// for them; the OS file cache keeps what is read. Same descriptor, same indexed bounds and size checks + /// as `load_resident_tensor`. `charged_bytes` is the mapped length (address space, not RAM). + #[cfg(target_os = "linux")] + #[allow(unsafe_code)] + pub(crate) fn map_resident_tensor( + &mut self, + tensor_number: usize, + ) -> std::result::Result { + let (tensor_offset, tensor_bytes) = { + let tensor = self.index.tensors.get(tensor_number).ok_or_else(|| { + ResidentLoadError::Source("GGUF tensor index is out of bounds".into()) + })?; + (tensor.offset, tensor.bytes) + }; + let length = + usize::try_from(tensor_bytes).map_err(|e| ResidentLoadError::Source(e.into()))?; + if length == 0 { + return Err(ResidentLoadError::Source("resident tensor is empty".into())); + } + self.stream_tensor(tensor_number, 0, 0, |_| Ok(())) + .map_err(ResidentLoadError::Source)?; + let absolute = self + .index + .summary + .data_start + .checked_add(tensor_offset) + .ok_or_else(|| ResidentLoadError::Source("GGUF tensor offset overflow".into()))?; + if absolute + .checked_add(tensor_bytes) + .is_none_or(|end| end > self.index.summary.file_size) + { + return Err(ResidentLoadError::Source("GGUF tensor exceeds indexed file".into())); + } + let page = rustix::param::page_size() as u64; + let map_offset = absolute & !(page - 1); + let start = usize::try_from(absolute - map_offset) + .map_err(|e| ResidentLoadError::Source(e.into()))?; + let map_len = start + .checked_add(length) + .ok_or_else(|| ResidentLoadError::Source("mapping length overflow".into()))?; + self.check_size().map_err(ResidentLoadError::Source)?; + // SAFETY: a fresh read-only shared mapping of the retained verified descriptor at a page-aligned + // offset inside the indexed file; the kernel picks the address. No existing memory is replaced. + let base = unsafe { + rustix::mm::mmap( + std::ptr::null_mut(), + map_len, + rustix::mm::ProtFlags::READ, + rustix::mm::MapFlags::SHARED, + &self.file, + map_offset, + ) + } + .map_err(|e| ResidentLoadError::Source(Box::new(std::io::Error::from(e))))?; + let span = FileSpan { base, map_len, start, len: length }; + self.check_size().map_err(ResidentLoadError::Source)?; + let source = match self.resident_source_id { + Some(source) => source, + None => { + let source = next_source_id().map_err(ResidentLoadError::Source)?; + self.resident_source_id = Some(source); + source + } + }; + Ok(ResidentTensor { + source, + tensor_number, + bytes: ResidentStorage::Mapped(span), + charged_bytes: length, + }) + } /// Copies a real source-owned bank span, with unchanged indexed bounds and /// same-FD pre/post size checks. A hit intentionally does not seek/read FD. pub(crate) fn copy_resident_tensor( @@ -132,6 +263,7 @@ impl VerifiedGgufFile { .ok_or("resident tensor offset overflow")?; let selected = resident .bytes + .as_slice() .get(first..end) .ok_or("resident tensor extent")?; self.check_size()?; @@ -186,7 +318,7 @@ impl VerifiedGgufFile { Ok(ResidentTensor { source, tensor_number, - bytes, + bytes: ResidentStorage::Owned(bytes), charged_bytes, }) } @@ -207,7 +339,7 @@ impl ResidentTensor { std::rc::Rc::new(self) } pub(crate) fn retained_bytes(&self) -> &[u8] { - &self.bytes + self.bytes.as_slice() } pub(crate) const fn retention_metadata_bytes() -> usize { std::mem::size_of::() + 2 * std::mem::size_of::() @@ -323,4 +455,64 @@ mod retained_lease_test { drop(lease); std::fs::remove_file(path).unwrap(); } + + /// The low-RAM source maps the verified file instead of copying it: the same bytes, the same retained-owner + /// checks, and the mapping outlives the source handle like the owned copy does. + #[cfg(target_os = "linux")] + #[test] + fn mapped_tensor_is_the_files_bytes_and_a_retained_owner() { + let nonce = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let path = std::env::temp_dir().join(format!( + "strata-bank-map-{}-{nonce}.gguf", + std::process::id() + )); + let mut bytes = b"GGUF".to_vec(); + bytes.extend(3u32.to_le_bytes()); + bytes.extend(1u64.to_le_bytes()); + bytes.extend(0u64.to_le_bytes()); + let name = b"public.mapped.owner"; + bytes.extend((name.len() as u64).to_le_bytes()); + bytes.extend(name); + bytes.extend(1u32.to_le_bytes()); + bytes.extend(16u64.to_le_bytes()); + bytes.extend(0u32.to_le_bytes()); + bytes.extend(0u64.to_le_bytes()); + bytes.resize(bytes.len().div_ceil(32) * 32, 0); + for word in [0x80000000u32, 0x3f800000, 0xbf800000, 0x40490fdb] + .into_iter() + .cycle() + .take(16) + { + bytes.extend(word.to_le_bytes()); + } + std::fs::write(&path, &bytes).unwrap(); + let hex = Sha256::digest(&bytes) + .iter() + .map(|b| format!("{b:02x}")) + .collect::(); + let digest = format!("sha256:{hex}"); + let mut source = VerifiedGgufFile::open(&path, &digest).unwrap(); + let copy = source.load_resident_tensor(0, 64).unwrap(); + let mapped = source.map_resident_tensor(0).unwrap(); + assert!(mapped.file_mapped() && !copy.file_mapped()); + assert_eq!(mapped.len(), 64); + assert_eq!(mapped.charged_bytes(), 64); + let mapped = mapped.into_retained(); + assert_eq!(mapped.retained_bytes(), copy.into_retained().retained_bytes()); + assert_eq!(mapped.retained_bytes().as_ptr() as usize % 16, 0); + source.validate_retained_tensor(&mapped).unwrap(); + let out = source + .copy_resident_tensor(&mapped, 16, vec![0u8; 16].into_boxed_slice()) + .unwrap(); + assert_eq!(&*out, &mapped.retained_bytes()[16..32]); + let expected = mapped.retained_bytes().to_vec(); + drop(source); + // the mapping is its own owner, like the owned copy + assert_eq!(mapped.retained_bytes(), expected); + drop(mapped); + std::fs::remove_file(path).unwrap(); + } } diff --git a/crates/model-format/src/qwen4exp_digest_capture.rs b/crates/model-format/src/qwen4exp_digest_capture.rs index db4b7e0a..16f55b98 100644 --- a/crates/model-format/src/qwen4exp_digest_capture.rs +++ b/crates/model-format/src/qwen4exp_digest_capture.rs @@ -392,6 +392,7 @@ impl Qwen4ExpArtifact { shard0_sha256: self.shards[0].artifact_sha256(), copied_spans: 0, copied_bytes: 0, + file_mapped: false, }; self.resident_experts = Some(ResidentExpertBank { banks: Rc::new(capture.banks), diff --git a/crates/model-format/src/qwen4exp_expert_source_bank.rs b/crates/model-format/src/qwen4exp_expert_source_bank.rs index 02f948c8..00cd6bce 100644 --- a/crates/model-format/src/qwen4exp_expert_source_bank.rs +++ b/crates/model-format/src/qwen4exp_expert_source_bank.rs @@ -26,6 +26,8 @@ pub struct ResidentExpertSourceReport { pub shard0_sha256: [u8; 32], pub copied_spans: u64, pub copied_bytes: u64, + /// The banks are read-only shared mappings of shard 0 (`load_mapped_expert_source`), not RAM copies. + pub file_mapped: bool, } #[derive(Debug)] pub enum ResidentExpertSourceError { @@ -329,6 +331,7 @@ impl Qwen4ExpArtifact { shard0_sha256: self.shards[0].artifact_sha256(), copied_spans: 0, copied_bytes: 0, + file_mapped: false, }; self.resident_experts = Some(ResidentExpertBank { banks: Rc::new(banks), @@ -341,6 +344,86 @@ impl Qwen4ExpArtifact { pub fn resident_expert_source_report(&self) -> Option { self.resident_experts.as_ref().map(|bank| bank.report()) } + + /// The low-RAM source (the Original's `--mmap-experts`, GGUF shards in place: generate.cpp + /// `src.set_gguf(o.native_preset)` + `FileExpertSource::open`): the same 144 banks, but each is a read-only + /// shared mapping of shard 0 instead of a RAM copy. Nothing is read at load; the OS file cache holds the + /// experts that are used and can give the memory back. The bytes are the verified file's, so every consumer + /// sees exactly what the resident copy would hold. No `MemAvailable` admission: the mapping commits no RAM. + #[cfg(target_os = "linux")] + pub fn load_mapped_expert_source( + &mut self, + ) -> Result { + if self.resident_experts.is_some() { + return Err(ResidentExpertSourceError::AlreadyEnabled); + } + if self.topology.block_count != 48 || self.topology.expert_count != 512 { + return Err(ResidentExpertSourceError::Geometry); + } + let mut banks = Vec::new(); + banks + .try_reserve_exact(BANKS) + .map_err(|_| ResidentExpertSourceError::Allocation)?; + let mut source_bytes = 0usize; + for layer in 0..48 { + for role in [ + LayerRole::FfnGateExperts, + LayerRole::FfnUpExperts, + LayerRole::FfnDownExperts, + ] { + let role = TensorRole::Layer { layer, role }; + let tensor = self + .roles + .get(&role) + .ok_or(ResidentExpertSourceError::Geometry)?; + let descriptor = checked_descriptor(role, tensor)?; + source_bytes = source_bytes + .checked_add(descriptor.bytes) + .ok_or(ResidentExpertSourceError::Geometry)?; + if source_bytes as u64 > SOURCE_CAP { + return Err(ResidentExpertSourceError::MemoryAdmission); + } + let mapped = self.shards[0] + .map_resident_tensor(descriptor.tensor_number) + .map_err(|error| match error { + gguf::ResidentLoadError::Allocation => ResidentExpertSourceError::Allocation, + gguf::ResidentLoadError::Budget => ResidentExpertSourceError::MemoryAdmission, + gguf::ResidentLoadError::Source(error) => { + ResidentExpertSourceError::Read(BindingError::Io(error)) + } + })?; + if mapped.len() != descriptor.bytes { + return Err(ResidentExpertSourceError::Geometry); + } + banks.push(Bank { + descriptor, + tensor: mapped.into_retained(), + }); + } + } + if banks.len() != BANKS { + return Err(ResidentExpertSourceError::Geometry); + } + let report = ResidentExpertSourceReport { + source_bytes: source_bytes as u64, + charged_bytes: source_bytes as u64, + bank_count: BANKS as u32, + source_cap_bytes: SOURCE_CAP, + observed_mem_available_bytes: 0, + future_headroom_bytes: 0, + shard0_sha256: self.shards[0].artifact_sha256(), + copied_spans: 0, + copied_bytes: 0, + file_mapped: true, + }; + self.resident_experts = Some(ResidentExpertBank { + banks: Rc::new(banks), + report, + copied_spans: Cell::new(0), + copied_bytes: Cell::new(0), + }); + Ok(report) + } } #[path = "qwen4exp_digest_capture.rs"] @@ -363,6 +446,11 @@ impl ResidentExpertBankLease { pub fn charged_source_bytes(&self) -> u64 { self.report.charged_bytes } + /// The banks are read-only shared mappings of the verified shard (the low-RAM source): page-locking them + /// would read and lock the whole file in RAM, so their consumers copy from pageable memory instead. + pub fn file_mapped(&self) -> bool { + self.report.file_mapped + } pub fn retention_metadata_bytes(&self) -> usize { // Complete lease was minted only after this checked closed bound. BANKS * gguf::ResidentTensor::retention_metadata_bytes() @@ -392,6 +480,9 @@ impl ResidentExpertBankMember { pub fn bytes(&self) -> &[u8] { self.tensor.retained_bytes() } + pub fn file_mapped(&self) -> bool { + self.tensor.file_mapped() + } pub fn belongs_to_lease(&self, lease: &ResidentExpertBankLease) -> bool { slot(self.descriptor.role) .ok() From 2bd2c147f9ef53a24fe0070209249e6fe587dd38 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 11:27:08 +0200 Subject: [PATCH 3/8] feat(kar): admit the pinned KAR archive as a read-only file instead of a 55 GB sealed memfd `InheritedKarArchive::open_read_only_file`: the archive stays on the SSD and only the PLE rows a request reads pass through the OS file cache, like the Original's PleTable::open_kar (kar_open with payload verification, then a read-only mapping of the file). The sealed memfd keeps 55,295,529,472 bytes of shmem for the life of the process. Full SHA-256 and payload CRCs are still verified at load; immutability afterwards is the operator's (regular file, one link, owned by this user, no write bits), and the reader is reopened through /proc/self/fd with the inode rechecked. Co-Authored-By: Claude Opus 5.5 --- .../src/model_binding/qwen4exp_kar_ple.rs | 98 ++++++++++++++++++- 1 file changed, 95 insertions(+), 3 deletions(-) diff --git a/crates/leleka-runtime/src/model_binding/qwen4exp_kar_ple.rs b/crates/leleka-runtime/src/model_binding/qwen4exp_kar_ple.rs index 1221dd2f..fce9e9fe 100644 --- a/crates/leleka-runtime/src/model_binding/qwen4exp_kar_ple.rs +++ b/crates/leleka-runtime/src/model_binding/qwen4exp_kar_ple.rs @@ -17,6 +17,8 @@ const PINNED_ARCHIVE_BYTES: u64 = 55_295_529_472; pub struct InheritedKarArchive { archive: File, provenance: File, + /// `open_read_only_file`: an ordinary read-only file instead of a sealed memfd (see there). + file_backed: bool, } impl InheritedKarArchive { #[cfg(target_os = "linux")] @@ -30,9 +32,44 @@ impl InheritedKarArchive { Ok(Self { archive, provenance, + file_backed: false, }) } + /// The low-RAM form of the same pinned archive: the archive stays an ordinary file on the SSD and only the + /// rows a request reads pass through the OS file cache, like the Original's `PleTable::open_kar` (ngram.cpp: + /// `kar_open` with payload verification, then a read-only mapping of the file). A sealed memfd copy keeps + /// all 55,295,529,472 bytes in shmem for the life of the process, which a 32-48 GB PC cannot hold. + /// + /// Weaker than the seal and therefore explicit: the full SHA-256 and every payload CRC are still verified at + /// load (`load_pinned_inherited_archive`), but immutability afterwards rests on the operator: the file must + /// be a regular file owned by this user with no write permission bits (`chmod a-w`) and a single link, and + /// every later row read rechecks its length and inode. + #[cfg(target_os = "linux")] + pub fn open_read_only_file(archive: &Path, provenance: PathBuf) -> Result { + let archive = open_read_only_archive(archive, PINNED_ARCHIVE_BYTES) + .map_err(|_| "KAR archive file is not the pinned read-only archive")?; + let provenance = private_copy::open_regular(&provenance, None) + .map_err(|_| "KAR provenance is not a regular file")?; + verify_open_provenance(&provenance, PROVENANCE_DIGEST) + .map_err(|_| "KAR provenance verification failed")?; + Ok(Self { + archive, + provenance, + file_backed: true, + }) + } + + #[cfg(not(target_os = "linux"))] + pub fn open_read_only_file(_archive: &Path, _provenance: PathBuf) -> Result { + Err("KAR archive file requires Linux") + } + + /// True for `open_read_only_file`. + pub fn file_backed(&self) -> bool { + self.file_backed + } + #[cfg(not(target_os = "linux"))] pub fn open(_fd: u32, _provenance: PathBuf) -> Result { Err("inherited KAR archive requires Linux") @@ -69,6 +106,56 @@ fn open_sealed_archive_fd(fd: u32, expected_bytes: u64) -> InputResult { Ok(file) } +/// An ordinary archive file for `InheritedKarArchive::open_read_only_file`: regular, the pinned length, one +/// link, owned by this user, no write permission bits for anyone. +#[cfg(target_os = "linux")] +fn open_read_only_archive(path: &Path, expected_bytes: u64) -> InputResult { + use std::os::unix::fs::OpenOptionsExt; + let file = std::fs::OpenOptions::new() + .read(true) + .custom_flags(0x800 | 0x20000) // O_NONBLOCK (reject FIFOs), O_NOFOLLOW + .open(path) + .map_err(private_copy::provenance_error)?; + check_read_only_archive(&file, expected_bytes)?; + Ok(file) +} + +#[cfg(target_os = "linux")] +fn check_read_only_archive(file: &File, expected_bytes: u64) -> InputResult<()> { + use std::os::unix::fs::MetadataExt; + let meta = file.metadata().map_err(private_copy::provenance_error)?; + if !meta.is_file() || meta.len() != expected_bytes || meta.nlink() != 1 { + return Err(InputBindingError::Range); + } + // /proc/self is owned by this process's effective user + let me = std::fs::metadata("/proc/self").map_err(private_copy::provenance_error)?.uid(); + if meta.mode() & 0o222 != 0 || meta.uid() != me { + return Err(InputBindingError::Metadata); + } + Ok(()) +} + +/// An independent reader of the admitted read-only archive (same inode, rechecked). +#[cfg(target_os = "linux")] +fn reopen_read_only_archive(source: &File, expected_bytes: u64) -> InputResult { + use std::os::fd::AsRawFd; + use std::os::unix::fs::{MetadataExt, OpenOptionsExt}; + let file = std::fs::OpenOptions::new() + .read(true) + .custom_flags(0x800) + .open(format!("/proc/self/fd/{}", source.as_raw_fd())) + .map_err(private_copy::provenance_error)?; + let (a, b) = ( + source.metadata().map_err(private_copy::provenance_error)?, + file.metadata().map_err(private_copy::provenance_error)?, + ); + if a.dev() != b.dev() || a.ino() != b.ino() { + return Err(InputBindingError::Metadata); + } + check_read_only_archive(&file, expected_bytes)?; + Ok(file) +} + #[cfg(target_os = "linux")] fn verify_open_provenance(file: &File, expected_digest: [u8; 32]) -> InputResult<()> { use sha2::{Digest, Sha256}; @@ -107,9 +194,14 @@ pub(crate) fn load_pinned_inherited_archive( ) -> InputResult { use std::os::fd::AsRawFd; let profile = pinned_profile().map_err(|e| input_failure(LoadPhase::Profile, e))?; - let fd = u32::try_from(source.archive.as_raw_fd()).map_err(|_| InputBindingError::Range)?; - let reader = open_sealed_archive_fd(fd, PINNED_ARCHIVE_BYTES) - .map_err(|e| input_failure(LoadPhase::Source, e))?; + let reader = if source.file_backed { + reopen_read_only_archive(&source.archive, PINNED_ARCHIVE_BYTES) + .map_err(|e| input_failure(LoadPhase::Source, e))? + } else { + let fd = u32::try_from(source.archive.as_raw_fd()).map_err(|_| InputBindingError::Range)?; + open_sealed_archive_fd(fd, PINNED_ARCHIVE_BYTES) + .map_err(|e| input_failure(LoadPhase::Source, e))? + }; verify_open_provenance(&source.provenance, PROVENANCE_DIGEST) .map_err(|e| input_failure(LoadPhase::Provenance, e))?; let inspection = leleka_model_format::kar::KarInspection::inspect(reader) From bbba0f231db961b2eb300411463fcccff21e80c5 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 11:27:46 +0200 Subject: [PATCH 4/8] bench(laptop): paired Original/port harness on fixed pre-tokenized prompts * tokenizer example `chat_tokens`: one user turn per line, thinking off, to comma-separated IDs, so both engines get exactly the same token IDs (benchmarks/laptop/prompts.txt: 3 prompts, 78-88 tokens). * leleka-runtime ignored test `original_serve_laptop_bench`: opens the Original serve stack with the low-RAM sources (mapped experts, read-only KAR file; resident/memfd still selectable), serves every prompt REPEAT times greedily and prints TTFT, prompt/decode phase times, prefill/decode tok/s, memory and the output IDs of the first pass. * scripts/laptop: original_bench.sh drives the unmodified `strata generate --serve` (setup.py's IQ3_S arguments, conversation cache off, one GEN at a time, TTFT to the first T line); port_bench.sh runs the test; monitor.sh samples process RSS/anon/file/shmem/locked/pinned and GPU VRAM once a second. Co-Authored-By: Claude Opus 5.5 --- benchmarks/laptop/prompts.txt | 4 + crates/leleka-runtime/src/backend.rs | 3 + .../src/backend_original_serve_laptop.rs | 156 ++++++++++++++++++ crates/tokenizer/examples/chat_tokens.rs | 52 ++++++ scripts/laptop/monitor.sh | 18 ++ scripts/laptop/original_bench.sh | 68 ++++++++ scripts/laptop/port_bench.sh | 33 ++++ 7 files changed, 334 insertions(+) create mode 100644 benchmarks/laptop/prompts.txt create mode 100644 crates/leleka-runtime/src/backend_original_serve_laptop.rs create mode 100644 crates/tokenizer/examples/chat_tokens.rs create mode 100644 scripts/laptop/monitor.sh create mode 100644 scripts/laptop/original_bench.sh create mode 100644 scripts/laptop/port_bench.sh diff --git a/benchmarks/laptop/prompts.txt b/benchmarks/laptop/prompts.txt new file mode 100644 index 00000000..8432dab9 --- /dev/null +++ b/benchmarks/laptop/prompts.txt @@ -0,0 +1,4 @@ +# Laptop profile paired prompts (docs/laptop-profile.md): one user turn per line, thinking off, 128 new tokens. +Write a Python function that converts an ISO-8601 duration string such as P3DT4H12M5S into a total number of seconds. Reject years and months with a clear ValueError, validate the whole input with one regular expression, and add three short doctest examples. After the code, explain in two sentences which edge cases you considered and why. +Explain to a junior engineer how a write-ahead log makes a database safe against crashes. Cover what is written before the data pages change, how recovery replays or discards log records after a power loss, why the order of fsync calls matters, and one common performance trade-off. Use a short numbered list followed by a one-paragraph summary. +You are reviewing a pull request that changes a Rust HTTP server to stream responses as server-sent events. List the five most important things to check for correctness, including client cancellation, backpressure, errors that happen after the first byte was sent, and the terminal event. For each item, describe one concrete test you would write. diff --git a/crates/leleka-runtime/src/backend.rs b/crates/leleka-runtime/src/backend.rs index 27e14fc9..60806c85 100644 --- a/crates/leleka-runtime/src/backend.rs +++ b/crates/leleka-runtime/src/backend.rs @@ -3470,6 +3470,9 @@ mod singleload_proof; #[cfg(all(test, target_os = "linux", target_arch = "x86_64"))] #[path = "backend_original_serve_smoke.rs"] mod original_serve_smoke; +#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))] +#[path = "backend_original_serve_laptop.rs"] +mod original_serve_laptop; #[cfg(all(test, target_os = "linux", target_arch = "x86_64"))] #[path = "resident_mmq_model_proof.rs"] diff --git a/crates/leleka-runtime/src/backend_original_serve_laptop.rs b/crates/leleka-runtime/src/backend_original_serve_laptop.rs new file mode 100644 index 00000000..3c59d600 --- /dev/null +++ b/crates/leleka-runtime/src/backend_original_serve_laptop.rs @@ -0,0 +1,156 @@ +//! Opt-in real-model bench of the Original serve stack in the laptop profile (docs/laptop-profile.md): the +//! low-RAM sources instead of the server's resident ones, and fixed pre-tokenized prompts so the Original +//! (`strata generate --serve`, `GEN `) can be run on exactly the same token IDs. +//! +//! * `LELEKA_LAPTOP_BENCH=yes` explicit opt-in (one GPU, one model load); +//! * `LELEKA_STRA169_IQ3S_SHARD0`, `_SHARD1` the pinned GGUF shards; +//! * `LELEKA_LAPTOP_KAR_FILE` (read-only regular file, `InheritedKarArchive::open_read_only_file`) or +//! `LELEKA_STRA169_KAR_FD` (the sealed memfd), and `LELEKA_STRA169_KAR_PROVENANCE`; +//! * `LELEKA_STRA169_MTP_PACK`, `LELEKA_STRA169_MTP_STAGING`; +//! * `LELEKA_LAPTOP_EXPERTS` = `mapped` (default: read-only shared mapping of shard 0, the Original's +//! `--mmap-experts` with the GGUF in place) or `resident` (the 50 GB RAM copy of the server profile); +//! * `LELEKA_LAPTOP_PROMPT_IDS` file, one comma-separated token-ID line per prompt; +//! * optional `LELEKA_LAPTOP_MAX_NEW` (128), `_REPEAT` (2), `_SPEC_MIN_P` (0.5, setup.py's), `_CPU_WORKERS` (7: the Original's default on an +//! 8-core CPU, one core for the host loop), `_MAX_CONTEXT` (8192), `LELEKA_ORIGINAL_SERVE_CAPACITY` (2048), +//! `LELEKA_ORIGINAL_SERVE_BUDGET_GIB` (15), `LELEKA_ORIGINAL_SERVE_KV_RESIDENT` (default window), +//! `LELEKA_ORIGINAL_SERVE_RT_DIR`, and the VRAM expert tier's `LELEKA_ORIGINAL_SERVE_EXPERT_*` switches. +//! +//! Prints one `LAPTOP request` line per request (prompt tokens, TTFT, prompt and decode phase wall time, prefill +//! and decode tok/s) and the output IDs of the first pass. Greedy, no penalties, EOS stops. +//! +//! Run: `cargo test -p leleka-runtime --features cuda-driver[,sm86] --release -- --ignored --nocapture +//! original_serve_laptop_bench`. +use super::*; +use crate::qwen_forward::{ + original_serve_request::ServeRequest, + original_serve_stack::{OriginalServeStack, StackConfig}, +}; +use std::env; + +fn required_path(name: &str) -> PathBuf { + env::var_os(name).map(PathBuf::from).unwrap_or_else(|| panic!("missing operator-owned bench input {name}")) +} + +fn number(name: &str, default: usize) -> usize { + env::var(name).ok().map(|v| v.parse().unwrap_or_else(|_| panic!("{name} must be a count"))).unwrap_or(default) +} + +/// `VmRSS`, `VmHWM`, `RssAnon`, `RssFile`, `RssShmem`, `VmLck`, `VmPin` of this process in MiB. +fn memory_line() -> String { + let text = std::fs::read_to_string("/proc/self/status").unwrap_or_default(); + let mut out = Vec::new(); + for key in ["VmRSS:", "VmHWM:", "RssAnon:", "RssFile:", "RssShmem:", "VmLck:", "VmPin:"] { + if let Some(line) = text.lines().find(|l| l.starts_with(key)) { + let kib: u64 = line.split_ascii_whitespace().nth(1).and_then(|v| v.parse().ok()).unwrap_or(0); + out.push(format!("{}={}MiB", key.trim_end_matches(':'), kib / 1024)); + } + } + out.join(" ") +} + +fn elapsed(start: std::time::Instant) -> f64 { + start.elapsed().as_secs_f64() +} + +#[test] +#[ignore = "one explicitly scheduled real-model load and GPU (laptop profile)"] +fn original_serve_laptop_bench() { + assert!(env::var("LELEKA_LAPTOP_BENCH").is_ok_and(|v| v == "yes"), "explicit laptop bench opt-in required"); + let start = std::time::Instant::now(); + let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0).expect("pinned shard0 verification failed"); + let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 verification failed"); + eprintln!("LAPTOP load: shards verified in {:.1} s; {}", elapsed(start), memory_line()); + let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed"); + let eos = *artifact.tokenizer().special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); + let provenance = required_path("LELEKA_STRA169_KAR_PROVENANCE"); + let inherited = match env::var_os("LELEKA_LAPTOP_KAR_FILE") { + Some(path) => InheritedKarArchive::open_read_only_file(std::path::Path::new(&path), provenance).expect("read-only KAR admission failed"), + None => { + let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").expect("LELEKA_LAPTOP_KAR_FILE or LELEKA_STRA169_KAR_FD").parse().expect("invalid descriptor"); + InheritedKarArchive::open(fd, provenance).expect("inherited KAR admission failed") + } + }; + let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( + artifact, + &inherited, + &required_path("LELEKA_STRA169_MTP_PACK"), + &required_path("LELEKA_STRA169_MTP_STAGING"), + ) + .expect("actual pinned KAR+MTP binding failed"); + eprintln!("LAPTOP load: KAR ({}) + MTP bound at {:.1} s; {}", if inherited.file_backed() { "read-only file" } else { "sealed memfd" }, elapsed(start), memory_line()); + let experts = env::var("LELEKA_LAPTOP_EXPERTS").unwrap_or_else(|_| "mapped".to_owned()); + let report = match experts.as_str() { + "mapped" => binding.load_mapped_expert_source().expect("mapped expert source load failed"), + "resident" => binding.load_resident_expert_source().expect("resident expert source load failed"), + other => panic!("LELEKA_LAPTOP_EXPERTS must be mapped or resident, not {other}"), + }; + eprintln!("LAPTOP load: experts {experts} ({} bytes, file_mapped={}) at {:.1} s; {}", report.source_bytes, report.file_mapped, elapsed(start), memory_line()); + + let budget_gib = number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 15); + let driver = Driver::load().expect("CUDA driver load failed"); + let device = driver.device(0).expect("CUDA device 0 unavailable"); + let context = Rc::new(device.create_context(budget_gib << 30).expect("bounded Context unavailable")); + let mut config = StackConfig::new(number("LELEKA_LAPTOP_MAX_CONTEXT", 8192) as i64); + config.capacity = number("LELEKA_ORIGINAL_SERVE_CAPACITY", 2048); + config.cpu_workers = number("LELEKA_LAPTOP_CPU_WORKERS", 7) as i32; + if let Ok(v) = env::var("LELEKA_ORIGINAL_SERVE_KV_RESIDENT") { + config.kv_resident = v.parse().expect("LELEKA_ORIGINAL_SERVE_KV_RESIDENT must be a count"); + } + config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from); + config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment() + .expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"); + eprintln!("LAPTOP config: capacity {} cpu_workers {} max_context {} kv_resident {} budget {budget_gib} GiB tier {:?}", + config.capacity, config.cpu_workers, config.max_context, config.kv_resident, config.expert_tier); + let mut stack = match OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config) { + Ok(stack) => stack, + Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()), + }; + eprintln!("LAPTOP load: stack open at {:.1} s; {}", elapsed(start), memory_line()); + + let prompts: Vec> = std::fs::read_to_string(required_path("LELEKA_LAPTOP_PROMPT_IDS")) + .expect("prompt id file unreadable") + .lines() + .filter(|l| !l.trim().is_empty()) + .map(|l| l.split(',').map(|t| t.trim().parse().expect("token id")).collect()) + .collect(); + let max_new = number("LELEKA_LAPTOP_MAX_NEW", 128); + let repeat = number("LELEKA_LAPTOP_REPEAT", 2).max(1); + // setup.py's `--spec-min-p 0.5` (the draft-probability floor; greedy output does not depend on it) + let spec_min_p: f32 = env::var("LELEKA_LAPTOP_SPEC_MIN_P").ok().map(|v| v.parse().expect("LELEKA_LAPTOP_SPEC_MIN_P")).unwrap_or(0.5); + for pass in 0..repeat { + for (index, ids) in prompts.iter().enumerate() { + let request = ServeRequest::new(ids.clone(), max_new, None, 7, spec_min_p, vec![eos as i32]); + let mut out = Vec::new(); + let begun = std::time::Instant::now(); + let mut first = None; + let served = stack.serve(&request, &mut |round| { + if first.is_none() { + first = Some(begun.elapsed()); + } + out.extend_from_slice(round); + Ok(()) + }, &mut || false); + let total = begun.elapsed().as_secs_f64() * 1e3; + let ttft = first.map_or(total, |d| d.as_secs_f64() * 1e3); + let (prompt_ms, decode_ms) = stack.last_timing(); + match served { + Ok(outcome) => { + let prefill = if prompt_ms > 0.0 { ids.len() as f64 * 1e3 / prompt_ms } else { 0.0 }; + let decode = if decode_ms > 0.0 { out.len() as f64 * 1e3 / decode_ms } else { 0.0 }; + eprintln!("LAPTOP request p{} pass={pass} prompt={} produced={} rounds={} ttft_ms={ttft:.1} prompt_ms={prompt_ms:.1} \ + decode_ms={decode_ms:.1} total_ms={total:.1} prefill_tok_s={prefill:.1} decode_tok_s={decode:.2}; {}", + index + 1, ids.len(), out.len(), outcome.rounds, memory_line()); + if let Some(stats) = stack.expert_tier_stats() { + eprintln!("LAPTOP tier p{} pass={pass}: {}", index + 1, stats.describe()); + } + if pass == 0 { + eprintln!("LAPTOP output p{}: {}", index + 1, out.iter().map(|t| t.to_string()).collect::>().join(",")); + } + } + Err(e) => panic!("request p{} pass {pass} failed: {e:?} health={:?}", index + 1, stack.health()), + } + } + } + stack.close().expect("stack cleanup failed"); + Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed"); +} diff --git a/crates/tokenizer/examples/chat_tokens.rs b/crates/tokenizer/examples/chat_tokens.rs new file mode 100644 index 00000000..8329f791 --- /dev/null +++ b/crates/tokenizer/examples/chat_tokens.rs @@ -0,0 +1,52 @@ +//! Tokenize one user prompt per line into a Qwen chat turn with thinking off (the template's +//! `enable_thinking=false` generation prompt), printing one comma-separated token-ID line per prompt. +//! +//! `cargo run -p leleka-tokenizer --example chat_tokens -- TOKENIZER_DIR PROMPTS.txt` +//! +//! Used to feed the same token IDs to the Original (`strata generate --tokens-file`) and to the port in +//! paired laptop runs (docs/laptop-profile.md). Blank lines and lines starting with `#` are skipped. + +use std::{env, fs, path::Path, process::ExitCode}; + +use leleka_tokenizer::Tokenizer; + +fn main() -> ExitCode { + let args: Vec = env::args().collect(); + if args.len() != 3 { + eprintln!("usage: chat_tokens TOKENIZER_DIR PROMPTS.txt"); + return ExitCode::from(2); + } + let tokenizer = match Tokenizer::from_assets(Path::new(&args[1])) { + Ok(t) => t, + Err(e) => { + eprintln!("chat_tokens: tokenizer: {e}"); + return ExitCode::FAILURE; + } + }; + let text = match fs::read_to_string(&args[2]) { + Ok(t) => t, + Err(e) => { + eprintln!("chat_tokens: {}: {e}", args[2]); + return ExitCode::FAILURE; + } + }; + for line in text.lines().map(str::trim) { + if line.is_empty() || line.starts_with('#') { + continue; + } + let turn = format!( + "<|im_start|>user\n{line}<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" + ); + match tokenizer.encode(&turn, true) { + Ok(ids) => { + let ids: Vec = ids.iter().map(u32::to_string).collect(); + println!("{}", ids.join(",")); + } + Err(e) => { + eprintln!("chat_tokens: encode: {e}"); + return ExitCode::FAILURE; + } + } + } + ExitCode::SUCCESS +} diff --git a/scripts/laptop/monitor.sh b/scripts/laptop/monitor.sh new file mode 100644 index 00000000..972a435c --- /dev/null +++ b/scripts/laptop/monitor.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# Sample one process's memory and the GPU's VRAM once a second until it exits (laptop profile benches). +# monitor.sh PID OUT.tsv +# Columns: unix time, VRAM used MiB (nvidia-smi, whole GPU), VmRSS, RssAnon, RssFile, RssShmem, VmLck, VmPin (MiB), +# MemAvailable (MiB, whole VM). Prints the peaks when the process is gone. +set -u +pid="$1"; out="$2" +printf 't\tvram\trss\tanon\tfile\tshmem\tlck\tpin\tavail\n' > "$out" +field() { awk -v k="$1:" '$1==k {printf "%d", $2/1024}' "/proc/$pid/status" 2>/dev/null; } +while kill -0 "$pid" 2>/dev/null; do + vram=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits 2>/dev/null | head -1) + avail=$(awk '$1=="MemAvailable:" {printf "%d", $2/1024}' /proc/meminfo) + printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$(date +%s)" "${vram:-0}" "$(field VmRSS)" "$(field RssAnon)" \ + "$(field RssFile)" "$(field RssShmem)" "$(field VmLck)" "$(field VmPin)" "$avail" >> "$out" + sleep 1 +done +awk -F'\t' 'NR>1 {for (i=2;i<=9;i++) if ($i+0>m[i]) m[i]=$i+0; if (min==""||$9+0 "$OUT/$label.cmd" +mapfile -t prompts < <(grep -v '^[[:space:]]*$' "$PROMPTS") +t_start=$EPOCHREALTIME +coproc ENGINE { exec "$STRATA" "${args[@]}" 2> "$OUT/$label.stderr"; } +pid=$ENGINE_PID +bash "$here/monitor.sh" "$pid" "$OUT/$label.mem.tsv" > "$OUT/$label.mem.peak" & +mon=$! +: > "$OUT/$label.stdout" +ready="" +while IFS= read -r line <&"${ENGINE[0]}"; do + echo "$line" >> "$OUT/$label.stdout" + if [[ "$line" == READY* ]]; then ready=1; break; fi +done +if [[ -z "$ready" ]]; then echo "engine did not become ready"; tail -20 "$OUT/$label.stderr"; exit 1; fi +echo "load_s=$(echo "$EPOCHREALTIME - $t_start" | bc)" > "$OUT/$label.timing" +for ((pass = 0; pass < REPEAT; pass++)); do + for i in "${!prompts[@]}"; do + t0=$EPOCHREALTIME; first=""; toks=() + echo "GEN $MAX_NEW ${prompts[$i]}" >&"${ENGINE[1]}" + while IFS= read -r line <&"${ENGINE[0]}"; do + echo "$line" >> "$OUT/$label.stdout" + case "$line" in + T\ *) [[ -z "$first" ]] && first=$EPOCHREALTIME; toks+=("${line#T }") ;; + DONE*) break ;; + ERR*) echo "p$((i + 1)) pass=$pass: $line"; break ;; + esac + done + t1=$EPOCHREALTIME + ttft=$(echo "(${first:-$t1} - $t0) * 1000" | bc) + total=$(echo "($t1 - $t0) * 1000" | bc) + # DONE produced prompt prompt_ms decode_ms finish accepted offered resume hits look ram_reads file_reads file_MB + read -r _ produced n prompt_ms decode_ms finish acc off resume hits look ram files fmb <<< "$line" + printf 'p%d pass=%d prompt=%s produced=%s ttft_ms=%.1f prompt_ms=%s decode_ms=%s total_ms=%.1f prefill_tok_s=%.1f decode_tok_s=%.2f accept=%s/%s hits=%s/%s ram=%s files=%s file_MB=%s finish=%s\n' \ + $((i + 1)) "$pass" "$n" "$produced" "$ttft" "$prompt_ms" "$decode_ms" "$total" \ + "$(echo "$n * 1000 / $prompt_ms" | bc -l)" "$(echo "$produced * 1000 / $decode_ms" | bc -l)" \ + "$acc" "$off" "$hits" "$look" "$ram" "$files" "$fmb" "$finish" | tee -a "$OUT/$label.timing" + if [[ $pass -eq 0 ]]; then + (IFS=,; echo "output p$((i + 1)): ${toks[*]}") >> "$OUT/$label.outputs" + fi + done +done +echo QUIT >&"${ENGINE[1]}" +wait "$pid"; rc=$? +wait "$mon" || true +echo "exit=$rc" >> "$OUT/$label.mem.peak" +cat "$OUT/$label.mem.peak" diff --git a/scripts/laptop/port_bench.sh b/scripts/laptop/port_bench.sh new file mode 100644 index 00000000..88ad714a --- /dev/null +++ b/scripts/laptop/port_bench.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# Run the port's Original serve stack (laptop profile) on the same pre-tokenized prompts as original_bench.sh. +# port_bench.sh LABEL +# Environment: TEST_BIN (the built leleka-runtime test executable, `cargo test --release -p leleka-runtime +# --features sm86 --lib --no-run`), MODEL_DIR (the two GGUF shards), KAR (read-only archive file) and +# KAR_PROVENANCE, MTP (data/mtp-rt), MTP_STAGING (private 0700 dir), PROMPTS, OUT, CUBLAS12_LIB (dir with +# libcublas.so.12). Every LELEKA_* switch of backend_original_serve_laptop.rs passes through (experts mapped or +# resident, the VRAM tier's LELEKA_ORIGINAL_SERVE_EXPERT_*, MAX_NEW, REPEAT, CPU_WORKERS, ...). +set -uo pipefail +label="$1"; shift +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +: "${TEST_BIN:?}" "${MODEL_DIR:?}" "${KAR:?}" "${KAR_PROVENANCE:?}" "${MTP:?}" "${MTP_STAGING:?}" "${PROMPTS:?}" "${OUT:?}" +mkdir -p "$OUT" +mkdir -p -m 700 "$MTP_STAGING" +export LD_LIBRARY_PATH="${CUBLAS12_LIB:-$(ls -d "$HOME"/cublas-12.9.1.4/x/*/lib | head -1)}${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" +export LELEKA_LAPTOP_BENCH=yes +export LELEKA_STRA169_IQ3S_SHARD0="$MODEL_DIR/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf" +export LELEKA_STRA169_IQ3S_SHARD1="$MODEL_DIR/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf" +export LELEKA_LAPTOP_KAR_FILE="$KAR" LELEKA_STRA169_KAR_PROVENANCE="$KAR_PROVENANCE" +export LELEKA_STRA169_MTP_PACK="$MTP" LELEKA_STRA169_MTP_STAGING="$MTP_STAGING" +export LELEKA_LAPTOP_PROMPT_IDS="$PROMPTS" +env | grep -E '^LELEKA_' | sort > "$OUT/$label.env" +"$TEST_BIN" --ignored --exact backend::original_serve_laptop::original_serve_laptop_bench --nocapture --test-threads 1 \ + > "$OUT/$label.stdout" 2> "$OUT/$label.stderr" & +pid=$! +bash "$here/monitor.sh" "$pid" "$OUT/$label.mem.tsv" > "$OUT/$label.mem.peak" & +mon=$! +wait "$pid"; rc=$? +wait "$mon" || true +echo "exit=$rc" >> "$OUT/$label.mem.peak" +grep -hE '^LAPTOP (load|config|request|tier)' "$OUT/$label.stderr" "$OUT/$label.stdout" | sed -E 's/ (VmRSS|VmHWM|RssAnon|RssFile|RssShmem|VmLck|VmPin)=/ \1=/g' | tee "$OUT/$label.timing" +grep -hE '^LAPTOP output' "$OUT/$label.stderr" "$OUT/$label.stdout" | sed 's/^LAPTOP //' > "$OUT/$label.outputs" +cat "$OUT/$label.mem.peak" From 150561bd07a4259695c1174b859883eca69fca3e Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 11:37:19 +0200 Subject: [PATCH 5/8] feat(experts): resident RAM budget over the mapped bank (--resident-budget-gib) `LELEKA_ORIGINAL_SERVE_RESIDENT_BUDGET_GIB=N` (VRAM tier on, low-RAM file-mapped bank): after the cache is filled from the profile, the experts it does not hold are page-locked in RAM in profile order while their gate/up/down bytes fit N GiB, clamped like FileExpertSource::pin_cache_complement to MemAvailable less the 4 GiB headroom and a 0.25 GiB margin. The Original copies them into a page-locked arena; here the bank's own file pages are registered read-only in place (`MappedExpertBank::pin_resident`, merged page ranges per mapping, CU_MEMHOSTREGISTER_READ_ONLY), so they are read once, stay out of reclaim, and their copies are DMA. The bytes are unchanged. A budget that cannot be kept is a warning (#403) and leaves nothing registered. Co-Authored-By: Claude Opus 5.5 --- crates/cuda-driver/src/api.rs | 19 +++ crates/cuda-driver/src/mapped_expert_bank.rs | 113 ++++++++++++++++++ .../qwen_forward/original_serve_residency.rs | 52 ++++++++ 3 files changed, 184 insertions(+) diff --git a/crates/cuda-driver/src/api.rs b/crates/cuda-driver/src/api.rs index 492b8143..57731106 100644 --- a/crates/cuda-driver/src/api.rs +++ b/crates/cuda-driver/src/api.rs @@ -295,6 +295,19 @@ mod enabled { (self.inner.unregister)(bytes.as_ptr().cast_mut().cast()) }) } + /// Page-lock `len` bytes at page-aligned `start`, inside a read-only file mapping a bank retains + /// (CU_MEMHOSTREGISTER_READ_ONLY = 8; no device mapping): the pages are read in and stay resident, and + /// copies from them are DMA instead of staged. + pub(crate) fn register_read_only(&self, start: usize, len: usize) -> Result<()> { + // SAFETY: the caller passes a page range inside a live mapping it retains until `unregister_at`. + check("cuMemHostRegister_v2", unsafe { + (self.inner.register)(start as *mut c_void, len, 8) + }) + } + pub(crate) fn unregister_at(&self, start: usize) -> Result<()> { + // SAFETY: identical live registered base from `register_read_only`; all consumers drained. + check("cuMemHostUnregister", unsafe { (self.inner.unregister)(start as *mut c_void) }) + } pub(crate) fn copy_kernel( &self, actual: &mut MappedCopyArguments, @@ -461,6 +474,12 @@ impl MappedApi { pub(crate) fn unregister_bank(&self, _: &[u8]) -> Result<()> { Err(Error::UnsupportedPlatform) } + pub(crate) fn register_read_only(&self, _: usize, _: usize) -> Result<()> { + Err(Error::UnsupportedPlatform) + } + pub(crate) fn unregister_at(&self, _: usize) -> Result<()> { + Err(Error::UnsupportedPlatform) + } pub(crate) fn copy_kernel(&self, _: &mut MappedCopyArguments, _: Stream) -> Result<()> { Err(Error::UnsupportedPlatform) } diff --git a/crates/cuda-driver/src/mapped_expert_bank.rs b/crates/cuda-driver/src/mapped_expert_bank.rs index 0386cca3..11edb2a1 100644 --- a/crates/cuda-driver/src/mapped_expert_bank.rs +++ b/crates/cuda-driver/src/mapped_expert_bank.rs @@ -28,6 +28,9 @@ pub struct MappedExpertBank<'ctx> { /// are refused. This is the Original's `--mmap-experts` without `--resident-cpu-experts`: unpinned /// experts are copied, the OS file cache keeps the hot ones. pageable: bool, + /// The low-RAM RAM budget (`pin_resident`, the Original's `--resident-budget-gib`): page-aligned ranges of + /// the file mappings that are page-locked read-only, hottest experts first. Unregistered at close. + resident: std::cell::RefCell>, } impl Context<'_> { pub fn mapped_expert_bank<'ctx>( @@ -122,6 +125,7 @@ impl Context<'_> { page_charge: extra, closed: false, pageable, + resident: std::cell::RefCell::new(Vec::new()), }; let guard = self.enter()?; let operation = (|| { @@ -208,6 +212,112 @@ impl<'ctx> MappedExpertBank<'ctx> { pub fn pageable(&self) -> bool { self.pageable } + + /// The low-RAM resident budget (generate.cpp `--resident-budget-gib` / `--resident-experts`, + /// `FileExpertSource::pin_cache_complement`): keep the experts `ranked` (hottest first, the caller leaves out + /// the ones the VRAM cache holds) resident in RAM, page-locked, while their gate/up/down bytes fit + /// `budget_bytes`. The Original copies them into a page-locked arena; here the bank's own file pages are + /// page-locked in place (read-only registration), which reads them in once and keeps them out of the OS's + /// reclaim, and makes their copies DMA. Answers are unchanged: the bytes are the same file pages. Only for + /// a pageable bank, once. Returns (experts held, bytes registered including page rounding). + pub fn pin_resident(&self, ranked: &[(u8, u32)], budget_bytes: u64) -> Result<(usize, u64)> { + if !self.pageable || self.closed || self.context.is_poisoned() { + return Err(Error::UnsupportedQwenOperation); + } + if !self.resident.borrow().is_empty() { + return Err(Error::InvalidSize); + } + let page = api::page_size()?; + let mut ranges: Vec<(usize, usize)> = Vec::new(); + let mut used = 0u64; + let mut held = 0usize; + for &(layer, expert) in ranked { + if layer >= 48 || expert >= 512 { + return Err(Error::InvalidSize); + } + let spans: Vec<(usize, usize)> = (0..3) + .map(|role| { + let bytes = self.banks[usize::from(layer) * 3 + role].member.bytes(); + let each = bytes.len() / 512; + (bytes.as_ptr() as usize + expert as usize * each, each) + }) + .collect(); + let need: u64 = spans.iter().map(|&(_, n)| n as u64).sum(); + if used + need > budget_bytes { + continue; + } + used += need; + held += 1; + ranges.extend(spans); + } + // page-round each span inside its own mapping, then merge overlapping/adjacent ranges per mapping + let mut rounded: Vec<(usize, usize)> = Vec::new(); + for &(start, len) in &ranges { + let bank = self + .banks + .iter() + .map(|b| b.member.bytes()) + .find(|b| { + let s = b.as_ptr() as usize; + start >= s && start + len <= s + b.len() + }) + .ok_or(Error::InvalidSize)?; + let lo = (bank.as_ptr() as usize) & !(page - 1); + let hi = (bank.as_ptr() as usize + bank.len()).next_multiple_of(page); + let a = (start & !(page - 1)).max(lo); + let b = (start + len).next_multiple_of(page).min(hi); + rounded.push((a, b)); + } + rounded.sort_unstable(); + let mut merged: Vec<(usize, usize)> = Vec::new(); + for (a, b) in rounded { + match merged.last_mut() { + // only merge inside one mapping: distinct mappings are distinct VMAs (never contiguous by + // assumption), so an overlap or touch can only be the same tensor's pages + Some(last) if a <= last.1 && self.same_mapping(last.0, b - 1) => last.1 = last.1.max(b), + _ => merged.push((a, b)), + } + } + let api = self.api.as_ref().ok_or(Error::ContextPoisoned)?; + let guard = self.context.enter()?; + let mut registered = 0u64; + let mut result = Ok(()); + for &(a, b) in &merged { + match api.register_read_only(a, b - a) { + Ok(()) => { + self.resident.borrow_mut().push((a, b - a)); + registered += (b - a) as u64; + } + Err(e) => { + result = Err(e); + break; + } + } + } + let result = combine(result, guard.finish()); + if let Err(primary) = result { + // leave nothing half-built: the copies still work from pageable memory + let guard = self.context.enter()?; + let mut cleanup = Ok(()); + for (start, _) in std::mem::take(&mut *self.resident.borrow_mut()) { + cleanup = combine(cleanup, api.unregister_at(start)); + } + return combine(Err(primary), combine(cleanup, guard.finish())); + } + Ok((held, registered)) + } + fn same_mapping(&self, a: usize, b: usize) -> bool { + let page = api::page_size().unwrap_or(4096); + self.banks.iter().map(|x| x.member.bytes()).any(|x| { + let lo = (x.as_ptr() as usize) & !(page - 1); + let hi = (x.as_ptr() as usize + x.len()).next_multiple_of(page); + a >= lo && b < hi + }) + } + /// Bytes page-locked by `pin_resident`. + pub fn resident_bytes(&self) -> u64 { + self.resident.borrow().iter().map(|&(_, n)| n as u64).sum() + } /// The device alias of a registered span: refused for pageable banks. fn alias(&self, span: &ResidentExpertBankSpan) -> Result { let n = self.check(span)?; @@ -392,6 +502,9 @@ impl<'ctx> MappedExpertBank<'ctx> { let guard = self.context.enter()?; let mut result = Ok(()); if let Some(api) = &self.api { + for (start, _) in std::mem::take(&mut *self.resident.borrow_mut()) { + result = combine(result, api.unregister_at(start)); + } for bank in &mut self.banks { if bank.registered { let unregister = api.unregister_bank(bank.member.bytes()); diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs index 335dd696..4dd911f2 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs @@ -66,6 +66,8 @@ pub(crate) struct ExpertTierConfig { pub(crate) adapt_swaps: u32, /// `!--no-prefill-borrow` (the loan is taken only with a profile, as in the Original). pub(crate) prefill_borrow: bool, + /// `--resident-budget-gib` over the low-RAM file-mapped bank (0: off): see `pin_resident_complement`. + pub(crate) resident_budget_gib: f64, } impl ExpertTierConfig { pub(crate) fn off() -> Self { @@ -79,6 +81,7 @@ impl ExpertTierConfig { adapt_every: 4, adapt_swaps: 96, prefill_borrow: true, + resident_budget_gib: 0.0, } } /// The tier is on with a slot count or a profile. @@ -91,6 +94,7 @@ impl ExpertTierConfig { } pub(crate) fn validate(&self) -> Result<()> { if self.slots < -1 || !self.pcie_frac.is_finite() || !(0.0..=1.0).contains(&self.pcie_frac) || self.adapt_swaps > 4096 + || !self.resident_budget_gib.is_finite() || self.resident_budget_gib < 0.0 { return Err(Error::InvalidDimension); } @@ -137,6 +141,9 @@ impl ExpertTierConfig { if let Some(v) = var("PREFILL_BORROW") { config.prefill_borrow = !matches!(v.as_str(), "no" | "0" | "off"); } + if let Some(v) = var("RESIDENT_BUDGET_GIB") { + config.resident_budget_gib = v.parse().map_err(|_| Error::InvalidDimension)?; + } config.validate()?; Ok(config) } @@ -451,10 +458,55 @@ pub(in crate::qwen_forward) fn open_tier<'ctx>( let spans = moe.original_expert_spans(binding, u32::from(layer), u32::from(expert))?; cache.verify_slot(slot, &bank, &spans).map_err(|e| driver_error(&e))?; } + if config.resident_budget_gib > 0.0 && bank.pageable() { + pin_resident_complement(&bank, &cache, profile, config.resident_budget_gib)?; + } } Ok(Some((cache, filled))) } +/// generate.cpp `--resident-budget-gib N` over the low-RAM (file-mapped) bank: the experts the VRAM cache does +/// not hold, in profile order, page-locked in RAM while they fit N GiB, clamped like +/// `FileExpertSource::pin_cache_complement` to `MemAvailable` less the 4 GiB headroom and a 0.25 GiB margin. +fn pin_resident_complement( + bank: &leleka_cuda_driver::MappedExpertBank<'_>, + cache: &OriginalExpertCache<'_>, + profile: &OriginalRankedExperts, + budget_gib: f64, +) -> Result<()> { + const GIB: f64 = 1_073_741_824.0; + let available = std::fs::read_to_string("/proc/meminfo") + .ok() + .and_then(|t| { + t.lines() + .find(|l| l.starts_with("MemAvailable:")) + .and_then(|l| l.split_ascii_whitespace().nth(1)?.parse::().ok()) + }) + .map_or(0, |kib| kib * 1024); + let room = available.saturating_sub(4 << 30).saturating_sub(256 << 20); + let budget = ((budget_gib * GIB) as u64).min(room); + let ranked: Vec<(u8, u32)> = profile + .pairs() + .iter() + .filter(|&&(layer, expert)| cache.slot_of(usize::from(layer), usize::from(expert)) < 0) + .map(|&(layer, expert)| (layer as u8, u32::from(expert))) + .collect(); + let started = std::time::Instant::now(); + match bank.pin_resident(&ranked, budget) { + Ok((held, bytes)) => eprintln!( + "leleka-serve: resident RAM budget {:.2} GiB (asked {budget_gib:.2}, {:.2} GiB available): {held} experts the \ + VRAM cache does not hold page-locked by profile rank ({:.2} GiB) in {:.1} s; the rest read from the file", + budget as f64 / GIB, + available as f64 / GIB, + bytes as f64 / GIB, + started.elapsed().as_secs_f64() + ), + // #403: a budget that cannot be kept is a warning; every miss is read from the file pages instead + Err(e) => eprintln!("leleka-serve: WARNING: the resident RAM budget cannot be kept ({e:?}); experts are read from the file"), + } + Ok(()) +} + /// The serve stack's loan test (generate.cpp `fits_one`, fixed chunk): the prompt path's buffers for the /// configured chunk come from the cache's last `k` slots when `0 < k` and `k + 128 <= slots`. Unlike the /// Original the chunk is not halved to fit: the prompt executor is built for exactly this capacity. From 1ef80a1fb0f66928e1853938c796c4d5c5114852 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 11:39:05 +0200 Subject: [PATCH 6/8] bench(laptop): optional smaller process geometry (LELEKA_LAPTOP_CELLS, experimental) Co-Authored-By: Claude Opus 5.5 --- crates/leleka-runtime/src/backend_original_serve_laptop.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/leleka-runtime/src/backend_original_serve_laptop.rs b/crates/leleka-runtime/src/backend_original_serve_laptop.rs index 3c59d600..61fed1b5 100644 --- a/crates/leleka-runtime/src/backend_original_serve_laptop.rs +++ b/crates/leleka-runtime/src/backend_original_serve_laptop.rs @@ -86,6 +86,13 @@ fn original_serve_laptop_bench() { }; eprintln!("LAPTOP load: experts {experts} ({} bytes, file_mapped={}) at {:.1} s; {}", report.source_bytes, report.file_mapped, elapsed(start), memory_line()); + // Experimental: a process geometry of N cells instead of the trained 262144 (the Original sizes its KV by + // --max-context). Unscaled RoPE; must precede the first CUDA context user. + if let Ok(cells) = env::var("LELEKA_LAPTOP_CELLS") { + let cells: usize = cells.parse().expect("LELEKA_LAPTOP_CELLS must be a count"); + leleka_cuda_driver::configure_serving_context(cells, &Default::default()).expect("serving context refused"); + eprintln!("LAPTOP config: process geometry {cells} cells (experimental)"); + } let budget_gib = number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 15); let driver = Driver::load().expect("CUDA driver load failed"); let device = driver.device(0).expect("CUDA device 0 unavailable"); From c9845eed52b61ed35235da66066abbc3ca2de172 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 12:49:53 +0200 Subject: [PATCH 7/8] fix(experts): split bank copies at page-locked boundaries; Original bench without the subcommand With part of a file-mapped bank page-locked (`pin_resident`), an H2D copy that starts in registered pages and runs into unregistered ones is refused by the driver (CUDA_ERROR_INVALID_VALUE, first seen on the laptop run). `MappedExpertBank::copy_pieces` cuts a `cache_source` slice at every registered boundary and the four copy sites (prompt copy ring, cache fill, swap fill, PCIe staging) issue one copy per piece; one piece when nothing is locked, so the default path is unchanged. original_bench.sh: the `strata` binary takes the generate options directly. Co-Authored-By: Claude Opus 5.5 --- crates/cuda-driver/src/mapped_expert_bank.rs | 20 +++++++++++++++++ crates/cuda-driver/src/mmq_original_ring.rs | 9 +++++++- .../cuda-driver/src/original_expert_cache.rs | 22 +++++++++++-------- .../src/original_verify_gpu_plan.rs | 4 +++- scripts/laptop/original_bench.sh | 2 +- 5 files changed, 45 insertions(+), 12 deletions(-) diff --git a/crates/cuda-driver/src/mapped_expert_bank.rs b/crates/cuda-driver/src/mapped_expert_bank.rs index 11edb2a1..53b7f48b 100644 --- a/crates/cuda-driver/src/mapped_expert_bank.rs +++ b/crates/cuda-driver/src/mapped_expert_bank.rs @@ -314,6 +314,26 @@ impl<'ctx> MappedExpertBank<'ctx> { a >= lo && b < hi }) } + /// `bytes` (a `cache_source` slice) cut at every boundary of a `pin_resident` range, as (offset, length) + /// pieces: one H2D copy must not start in registered pages and run into unregistered ones (the driver + /// refuses it with CUDA_ERROR_INVALID_VALUE), so copy sites issue one copy per piece. One piece when nothing + /// is page-locked. + pub(crate) fn copy_pieces(&self, bytes: &[u8]) -> Vec<(usize, usize)> { + let resident = self.resident.borrow(); + let start = bytes.as_ptr() as usize; + let end = start + bytes.len(); + let mut cuts = vec![start, end]; + for &(a, n) in resident.iter() { + for c in [a, a + n] { + if c > start && c < end { + cuts.push(c); + } + } + } + cuts.sort_unstable(); + cuts.dedup(); + cuts.windows(2).map(|w| (w[0] - start, w[1] - w[0])).collect() + } /// Bytes page-locked by `pin_resident`. pub fn resident_bytes(&self) -> u64 { self.resident.borrow().iter().map(|&(_, n)| n as u64).sum() diff --git a/crates/cuda-driver/src/mmq_original_ring.rs b/crates/cuda-driver/src/mmq_original_ring.rs index 322c850b..a7871b94 100644 --- a/crates/cuda-driver/src/mmq_original_ring.rs +++ b/crates/cuda-driver/src/mmq_original_ring.rs @@ -474,7 +474,14 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { // Physical role-major bank layout requires three H2Ds. Same source // bytes and literal blob G/U/D layout; no decode/conversion/copy tmp. for (destination, source) in destinations.into_iter().zip(sources) { - api.copy_registered(destination, source, stream)?; + // one copy per registered/unregistered piece (`MappedExpertBank::copy_pieces`) + for (offset, bytes) in bank.copy_pieces(source) { + api.copy_registered( + destination.checked_subspan(source.len(), offset, bytes)?, + &source[offset..offset + bytes], + stream, + )?; + } } Ok(()) })?; diff --git a/crates/cuda-driver/src/original_expert_cache.rs b/crates/cuda-driver/src/original_expert_cache.rs index 7cf2f3ff..71b26ca3 100644 --- a/crates/cuda-driver/src/original_expert_cache.rs +++ b/crates/cuda-driver/src/original_expert_cache.rs @@ -313,8 +313,10 @@ impl<'ctx> OriginalExpertCache<'ctx> { let mut offset = 0usize; for span in spans { let source = bank.cache_source(span)?; - let destination = handle.checked_subspan(capacity, offset, source.len())?; - api.copy(destination.qwen_address(), source, stream)?; + for (at, bytes) in bank.copy_pieces(source) { + let destination = handle.checked_subspan(capacity, offset + at, bytes)?; + api.copy(destination.qwen_address(), &source[at..at + bytes], stream)?; + } offset += source.len(); } Ok(()) @@ -523,13 +525,15 @@ impl<'ctx> OriginalExpertCache<'ctx> { let mut offset = 0usize; for span in spans { let source = bank.cache_source(span)?; - let destination = handle.checked_subspan(capacity, offset, source.len())?; - self.attempted = true; - self.api.as_ref().ok_or(Error::ContextPoisoned)?.copy( - destination.qwen_address(), - source, - api::Stream(0), - )?; + for (at, bytes) in bank.copy_pieces(source) { + let destination = handle.checked_subspan(capacity, offset + at, bytes)?; + self.attempted = true; + self.api.as_ref().ok_or(Error::ContextPoisoned)?.copy( + destination.qwen_address(), + &source[at..at + bytes], + api::Stream(0), + )?; + } offset += source.len(); } Ok(()) diff --git a/crates/cuda-driver/src/original_verify_gpu_plan.rs b/crates/cuda-driver/src/original_verify_gpu_plan.rs index 57680a58..ac538157 100644 --- a/crates/cuda-driver/src/original_verify_gpu_plan.rs +++ b/crates/cuda-driver/src/original_verify_gpu_plan.rs @@ -244,7 +244,9 @@ impl<'ctx> schedule::OriginalVerifyCpuSink<'_, 'ctx> { let mut offset = staging + (q * stride) as u64; for part in s { let bytes = source.bank.cache_source(part)?; - copy.enqueue_copy_h2d(offset, bytes)?; + for (at, n) in source.bank.copy_pieces(bytes) { + copy.enqueue_copy_h2d(offset + at as u64, &bytes[at..at + n])?; + } offset += bytes.len() as u64; } } diff --git a/scripts/laptop/original_bench.sh b/scripts/laptop/original_bench.sh index 96ec36bd..39c20a01 100644 --- a/scripts/laptop/original_bench.sh +++ b/scripts/laptop/original_bench.sh @@ -17,7 +17,7 @@ MAX_NEW="${MAX_NEW:-128}"; REPEAT="${REPEAT:-2}"; MAX_CONTEXT="${MAX_CONTEXT:-81 mkdir -p "$OUT" shard1="$MODEL_DIR/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf" shard2="$MODEL_DIR/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf" -args=(generate --serve --pack "$PACK" --native "$shard1" --ple-gguf "$shard2" --expert-profile "$PROFILE" +args=(--serve --pack "$PACK" --native "$shard1" --ple-gguf "$shard2" --expert-profile "$PROFILE" --expert-cache auto --prefill auto --spec 4 --spec-min-p 0.5 --mtp "$MTP" --max-context "$MAX_CONTEXT" --kv int8 --prompt-cache 0 "$@") echo "strata ${args[*]}" > "$OUT/$label.cmd" From cfd80e9452b4a25f220e79c95af9ad831346abb4 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 13:08:44 +0200 Subject: [PATCH 8/8] docs: laptop profile (memory map, the Original's low-RAM modes, port gaps, paired laptop numbers) docs/laptop-profile.md: what lives in VRAM / RAM / NVMe on the RTX 3080 Laptop 16 GB + 48 GB machine for the Original and the port, why both GGUF shards are strictly needed, the WSL2 cgroup bug that keeps the Original's resident modes off there, the port's gaps and what this branch adds, and the measured arms (n = 6 each): unmodified Original 8.15 decode / 12.4 prefill tok/s / TTFT 7.2 s vs port 2.70 / 3.1 / 28.4 s on the same token IDs and KAR PLE; traced: all port decode time is in run_window (~1.0 s per verify window). Co-Authored-By: Claude Opus 5.5 --- docs/laptop-profile.md | 185 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 185 insertions(+) create mode 100644 docs/laptop-profile.md diff --git a/docs/laptop-profile.md b/docs/laptop-profile.md new file mode 100644 index 00000000..2eea5dd6 --- /dev/null +++ b/docs/laptop-profile.md @@ -0,0 +1,185 @@ +# Laptop profile: Qwen3.8-Flash-Next IQ3_S on a 16 GB laptop GPU + +**Status:** experimental profile, measured on one laptop. Nothing here is a production default or a quality claim. + +The target is the one machine below, not the RTX 5090 server: what has to live where, which of the Original's +low-memory modes apply, what the Rust port lacked to run there, and paired numbers on the same prompts. + +## Machine + +| | | +| --- | --- | +| CPU | Intel i9-11900H, 8 cores / 16 threads, AVX-512 (VNNI, VBMI) | +| RAM | 48 GB (47 GiB usable); WSL2 gets half by default: `MemTotal` 24,447,308 kB | +| GPU | NVIDIA GeForce RTX 3080 Laptop GPU, 16,384 MiB, sm_86, driver 617.42 (WDDM, WSL2 passthrough); 14.89 GiB free to CUDA in WSL with nothing running | +| Disk | NVMe, 1.2 TB free on C:; the WSL ext4 VHDX lives on it | +| Software | Windows 11 Pro 26200, WSL2 Ubuntu 24.04, CUDA 13.2.86 (nvcc), cuBLAS 13.4 (Original) / 12.9.1.4 (port), Rust 1.99, gcc 13.3 | + +Pinned host memory under this WSL2: `cudaHostAlloc` of 16 x 512 MiB and `cudaHostRegister` of 1-16 GiB all succeeded +(probe, 2026-10-16). The Original's setup.py comment "the driver pins only about 1 GB" under WSL is not true for this +driver; the limit is the VM's RAM. + +## Model components and where they can live + +Sizes are from the files (`native_experts.txt`, the MTP pack, the KAR provenance) and the Original's formulas. + +| component | size | must be | can be | +| --- | --- | --- | --- | +| routed experts (48 layers x 512, IQ2_S..IQ4_NL) | 50,292,326,400 B (46.84 GiB), blob 1.51-2.66 MB, mean 2.05 MB | read per token for the 10 routed experts of every layer | VRAM cache (hot), RAM (warm), SSD (cold, via the OS file cache or direct reads) | +| dense pack (attention, GDN, shared experts, routers, norms) | `dense.bin` 1,538,035,200 B | VRAM | - | +| native head (Q5_K `output.weight` 248,320 x 2,560) | 521,472,000 B (Original log) | VRAM | - | +| token embedding | ~0.4 GB (Q5_K) | read per token | mapped host memory | +| PLE n-gram table (`per_layer_token_embd`, 320,001,536 rows) | 28,800,138,240 B (90 B/row, GGUF shard 2) or ~16 GB of level-2 KAR parts (50 B/row) | 16 rows per token | SSD (direct reads) + a bounded row cache | +| MTP draft layer (`data/mtp-rt`) | dense 116,099,072 B + experts 707,788,800 B (802 MiB of VRAM loaded) + draft head 212.9 MiB (106,299-token CJK subset) | VRAM | - | +| QSA KV, INT8 | 1,056 B per cell per layer, 12 QSA layers + draft layer = ~13.7 KB per token: 8K 0.11 GB, 32K 0.45 GB, 128K 1.8 GB, 256K 3.6 GB | the attention window in VRAM | the rest in pinned RAM (`--kv-resident`) | +| prompt (prefill) buffers | Original: borrowed from expert-cache slots (`--prefill auto`); port arena 2.0 / 2.8 / 4.3 GiB at chunk 2048 / 4096 / 8192 | VRAM while a prompt is read | - | + +The routed experts are the whole problem: 46.84 GiB against 14.9 GiB of usable VRAM and 23 GiB of WSL RAM. + +### VRAM budget (16 GiB card, 14.9 GiB free to CUDA) + +Measured (logs of the runs below): + +| | Original (`--expert-cache auto`, `--max-context 8192`) | port (Original serve stack, 8K ceiling) | +| --- | --- | --- | +| free before the expert cache | 9.67-9.73 GiB (after dense, native Q5_K head 521 MB, MTP 802 MiB, KV, state) | not printed; KV alone 0.391 GiB + 0.258 GiB prompt stage (262,144-cell geometry, 32K window) | +| reserve | `--vram-reserve-mib` 700 + 218 MiB draft head | `_VRAM_RESERVE_MIB` 700 + `_DECODE_RESERVE_MIB` 1024 (per-request verifier assembly) | +| expert slots | 4,597-4,632 slots, 8.76-8.83 GiB, sized per blob by the profile | 3,133 slots, 6.00 GiB | +| prompt path | borrows the last 1,965 slots (3.72 GiB) during a prompt | borrows the last 1,157 slots | +| left free | 459-461 MiB "with everything loaded" | (nvidia-smi peak 14,195 MiB used of 16,384) | +| decode hit rate (per request) | 48-77 % | 40-53 % of window entries on the GPU | + +Every GiB of VRAM is ~520 more cached experts (2.05 MB each) out of 24,576. + +### RAM budget (48 GB physical, 23.3 GiB in WSL by default) + +| | Original low-RAM resident mode | port before this work | port, laptop profile | +| --- | --- | --- | --- | +| experts | `--resident-experts`: the complement of the GPU cache (~36 GiB) does not fit, so the soft path keeps what fits (MemAvailable - 4 GiB headroom), hottest by the profile, page-locked; the rest through the OS file cache from the GGUF in place | 50 GB copied into RAM (`load_resident_expert_source`, needs MemAvailable >= 58 GB) and page-locked whole | read-only shared mapping of shard 0 (`load_mapped_expert_source`): nothing copied, the OS file cache keeps what is used | +| KAR archive | `--ple-kar`: mapped from the file | 55,295,529,472 B sealed memfd (shmem) for the life of the process | read-only file (`open_read_only_file`): file cache only | +| PLE (GGUF) | `--ple-io direct`: never in RAM, 1M-row (90 MB) cache | not used (KAR PLE only) | not used (KAR PLE only) | +| KV host copy | none at 8K (streaming is off below 64K, and setup turns it off under WSL) | 12 x 276,825,088 B = 3.32 GB pinned (always 262,144 cells) | same: 3.094 GiB pinned | + +**Under WSL2 the unmodified Original's resident modes do not engage.** `available_memory_bytes()` +(expert_source.cpp:219) requires the cgroup-v2 path of `/proc/self/cgroup` ("0::/init.scope") to exist unde +`/sys/fs/cgroup`; WSL2 mounts cgroup v2 at `/sys/fs/cgroup/unified` (hybrid layout), so it returns false and +`--resident-experts` / `--resident-budget-gib` fall back to plain mmap with "cannot determine available RAM". With +that check relaxed (2 lines, built as a separate labeled arm, not committed to `engine/strata`) the resident mode +works: "RAM budget 16.83 GiB: 8892 of the 38.07 GiB of experts the GPU cache does not hold", page-locked. + +### NVMe + +* PLE direct reads: 16 rows per token, one 4 KiB read each, ~64 KB/token: negligible at any decode rate. +* Experts: a miss that is neither in VRAM nor in RAM is a 1.5-2.7 MB read. That is the term that decides decode + speed once the RAM cannot hold the complement. +* The shards are verified once per start by the port (SHA-256 of 83.6 GB) and the KAR archive likewise (55.3 GB). + +## Files on the laptop and why + +| file | size | needed by | why | +| --- | --- | --- | --- | +| `qwen-iq3-s-l2-v4.kar` + provenance | 55.3 GB | port (KAR PLE), Original `--ple-kar` arm | the compressed PLE source; level 2 is lossy (an experimental arm, not the control) | +| `data/iq3_s` (dense.bin, index, native_experts.txt, tokenizer) | 1.5 GB | Original | its native pack | +| `data/mtp-rt` | 0.8 GB | both | the MTP draft layer | +| `data/expert-profile.bin` | 196,632 B, sha256 `8f59b4aa...6388975baf` | both (VRAM tier ranking, resident budget) | upstream `data/expert-profile.bin` at the pinned Strata commit `d9ab8435`; the imported subtree omits it | +| GGUF shard 1 | 54,817,524,224 B | both, strictly | the routed experts (no non-lossy compressed source exists: the KAR archive's level-2 experts have relative L2 ~0.33 and no quality gate), the dense GGUF projections and the native head | +| GGUF shard 2 | 28,800,138,432 B | both, strictly | Original: `--native` opens every shard of the split (`gguf_split_paths`, generate.cpp:1544) and `--ple-io direct` reads the table from it; port: `Qwen4ExpArtifact::bind` and `KarPleBinding::new` verify both shard digests and the PLE descriptor even when the rows come from KAR | + +All model files live on the WSL ext4 disk (`~/laptop/model`, `~/laptop/data`): `/mnt/c` is a 9p mount, far slowe +for mapped and direct reads. Nothing of it is in Git. + +## The Original's low-memory modes (engine/strata, unmodified) + +From `generate.cpp`, `expert_source.cpp`, `setup.py` and `docs/DETAILS.md`: + +| mode | flags | experts in RAM | fits this laptop | +| --- | --- | --- | --- | +| resident arena (default) | none | all 50.3 GB, pinned | no | +| low-RAM mapped | `--mmap-experts` (GGUF in place when the pack has no experts.bin) | OS file cache only | yes | +| low-RAM resident | `--resident-experts` = `--mmap-experts --resident-cpu-experts`, page-locked, 4 GiB headroom, soft | the complement of the GPU cache if it fits, else (#467) what fits, hottest by profile | yes (the "what fits" path) | +| RAM budget | `--resident-budget-gib N` | N GiB, hottest by profile, rest mapped; lookahead page prefetch of the next layer's predicted experts | yes | +| PLE | `--ple-io direct` (default) / `--ple-kar` (KAR-enabled build, experimental) | 90 MB row cache / file cache | yes | +| KV | `--kv int8`, `--kv-resident 32768` from 64K (setup turns streaming off under WSL) | none at 8K | yes | + +setup.py's argument set for IQ3_S: `--pack --native SHARD1 --ple-gguf SHARD2 --expert-profile data/expert-profile.bin +--expert-cache auto --prefill auto --spec 4 --spec-min-p 0.5 --mtp DIR --max-context N [--kv int8] [--resident-experts | +--mmap-experts]`. setup.py's table lists IQ3_S at 62 GB of RAM (48 GB: IQ2_XS or Q2_0); for a PC whose RAM cannot hold the +experts it picks the low-RAM resident variant, which is what is measured here. + +## What the port lacked for this laptop + +The Original serve stack of the port (`docs/original-serve.md`) opened only with server-sized sources: + +| mechanism | Original | port before | port now (this branch) | +| --- | --- | --- | --- | +| expert source without a 50 GB copy | `--mmap-experts`, GGUF in place | none: `load_resident_expert_source` copies 50 GB and needs MemAvailable >= 58 GB | `load_mapped_expert_source`: read-only shared mapping of shard 0; `MappedExpertBank` pageable mode (copies staged by the driver, no 50 GB `cuMemHostRegister`) | +| RAM budget / resident complement | `--resident-budget-gib`, `--resident-experts` | none | `LELEKA_ORIGINAL_SERVE_RESIDENT_BUDGET_GIB`: hottest non-VRAM experts page-locked in place (read-only registration of the file pages), same clamp | +| KAR PLE without holding the archive in RAM | `PleTable::open_kar` maps the file | 55.3 GB sealed memfd (shmem) | `InheritedKarArchive::open_read_only_file`: regular read-only file, verified at load | +| PLE direct from the GGUF | `--ple-io direct` | not ported (the Original serve stack needs KAR PLE) | not ported | +| VRAM expert tier sized for 16 GB | `--expert-cache auto` + profile | merged from `claude/expert-residency`, never run on a real model | used here, first real-model run | +| MTP | `--spec 4 --mtp` | present (`--mtp-rt-dir` / pack) | unchanged | +| KV sized by `--max-context` | yes | always 262,144 cells: 3.32 GB pinned host copy + 0.42 GB VRAM window at any ceiling | `LELEKA_LAPTOP_CELLS` (bench only, experimental) | +| sm_86 companion of `qsa_prompt_resolver.ptx` | n/a | stale after the kv-streaming reseal (2 arch_ptx tests failed; the 3080 would load the sm_120 image) | regenerated | +| lookahead page prefetch of predicted experts | `STRATA_LOOKAHEAD` | none | none | +| PCIe share of misses | `--pcie-frac 0.55` over the pinned complement | `_PCIE_FRAC` default 0 | 0 (pageable bank) | + +## Results, 2026-10-16 (one laptop, WSL2, n = 6 requests per arm) + +Workload: `benchmarks/laptop/prompts.txt` (3 user turns, thinking off, 88 / 83 / 78 tokens, tokenized once with +`chat_tokens` and fed as the same IDs to both engines), 128 new tokens, greedy, each prompt served twice in one +process (pass 0, pass 1), conversation cache off, `--max-context 8192` / ceiling 8192, INT8 KV, spec 4 + MTP +(`data/mtp-rt`), `--spec-min-p 0.5`, expert profile sha256 `8f59b4aa...` , 7 CPU expert workers. Cache state: no +root, so page caches could not be dropped; each arm starts with whatever the previous one left (recorded per arm +in `~/laptop/results/*.cache`). Engine: Original `engine/strata` at this branch, built for sm_86 with CUDA 13.2.86 +(`STRATA_NEXT_EXPERIMENTAL_KAR_PLE=ON`); port: branch `claude/laptop-profile`, `--features sm86`, release. Model: +the two IQ3_S shards (sha256 `4c1eb2ce...`, `316b46f3...`, verified on copy) and the level-2 KAR archive +(`536d612c...`). TTFT is measured from sending the request to the first emitted token; decode tok/s is produced +tokens over the decode phase; prefill tok/s is prompt tokens over the prompt phase. VRAM is nvidia-smi's peak fo +the whole GPU; RAM is the process's peak RSS (file-backed pages are reclaimable). + +| arm | PLE | experts | decode tok/s mean (median, range) | prefill tok/s mean | TTFT mean (range) | load to ready | peak VRAM | peak RSS (anon / file / shmem) | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | +| Original, `--resident-experts` (falls back to mmap under WSL2, see above) | GGUF direct | 4,632 VRAM slots + mmap | 5.64 (5.61, 4.45-7.12) | 8.7 | 10.0 s (8.0-12.0) | 34 s | 15,093 MiB | 22.4 GB (2.3 / 19.8 / 1.1) | +| Original, same, KAR PLE (`--ple-kar ... --ple-kar-gpu-cache-mib 64`) | KAR L2 | same | 8.15 (7.45, 6.75-10.17) | 12.4 | 7.2 s (4.6-9.1) | 150 s | 15,111 MiB | 22.9 GB (2.0 / 22.3 / 1.1) | +| Original + WSL cgroup fix (diagnostic arm), resident 16.83 GiB page-locked, KAR PLE | KAR L2 | 4,597 VRAM + 16.8 GiB RAM + mmap | 10.61 (10.93, 7.00-14.44) | 18.6 | 5.0 s (3.6-8.4) | 161 s | 15,111 MiB | 22.2 GB (1.9 / 15.1 / 18.1); MemAvailable fell to 2.2 GB | +| **port**, mapped experts + VRAM tier (profile, auto) | KAR L2 | 3,133 VRAM slots + mmap | **2.70** (2.63, 2.15-3.68) | **3.1** | **28.4 s** (20.6-36.6) | 212 s | 14,195 MiB | 20.5 GB (2.1 / 17.8 / 3.9) | +| port, adaptive swaps off, decode reserve 512 MiB | KAR L2 | 3,397 VRAM slots + mmap | 2.62 (2.67, 1.81-3.13) | 3.5 | 25.2 s (21.0-30.7) | 193 s | 14,709 MiB | 20.3 GB | +| port, + resident budget 16 GiB (clamped to 11.42 GiB page-locked) | KAR L2 | 3,133 VRAM + 11.4 GiB RAM + mmap | 2.39 (2.27, 1.48-3.44) | 3.1 | 30.2 s (21.2-46.9) | 214 s | 14,195 MiB | 14.0 GB | + +The paired comparison is row 2 (unmodified Original, the mode it actually runs in under WSL2) against row 4 (port): +same prompts, same PLE source, same profile, same VRAM-tier policy, greedy. **The port is 3.0x slower in decode +(2.70 vs 8.15 tok/s), 4.0x slower in prefill (3.1 vs 12.4 tok/s) and 3.9x later to the first token (28.4 vs 7.2 +s), with 1.5 GB less RAM, 0.9 GB less VRAM and 1,500 fewer VRAM expert slots.** Greedy outputs of the two agree on +the first 47 / 43 / 57 tokens of the three prompts and then diverge (GPU and CPU experts round differently and the +two place different experts on the GPU; the Original itself diverges from its GGUF-PLE run after 44 / 42 / 128 +tokens). This is not a quality gate. Rows 1 and 2 differ in the PLE source and in page-cache state at the start; +they are not a PLE A/B. + +Where the port's time goes (traced run, `LELEKA_BRINGUP_TRACE=1`, 3 prompts x 48 tokens): every decode millisecond +is inside `run_window` (62 windows, 62.8 s, 1,014 ms mean per verify window; begin_adaptation 13 ms, draft 10 ms, +everything else < 1 ms). The Original spends ~0.35-0.45 s per round on the same prompts. In the window, the +routed-expert CPU tier (`CpuExpertPool::run_entries`) prepares every job on the calling thread +(`prepare_scoped` copies the expert's three matrices out of the bank, i.e. page faults on the mapped shard, serially) +before the workers compute; the Original's pool reads the blobs where they are, fetches a layer's missing experts +on 8 threads and prefetches the next layer's predicted experts. Neither the resident budget nor turning adaptive +swaps off changed the port's rate beyond the run-to-run spread, which points at that path rather than at residency. +The prompt path likewise copies each borrowed expert with a host-blocking pageable `cuMemcpyHtoDAsync` on one +thread, where the Original stages through pinned buffers with helper threads. + +## Recommendations and open items + +1. Port next (largest measured gap): parallel, zero-copy CPU expert preparation over the mapped bank (literal + `expert_pool_dispatch_multi` + `FileExpertSource` fetch threads and routing lookahead), then pinned staging fo + the prompt copy ring. Re-measure with the same harness. +2. VRAM: the port leaves ~1,500 fewer expert slots than the Original; the 1 GiB per-request verifier reserve, the + 262,144-cell KV geometry (3.1 GiB pinned host + 0.65 GiB VRAM at an 8K ceiling) and the verifier being assembled + per request are the candidates (`LELEKA_LAPTOP_CELLS` exists in the bench for an experiment; not run here). +3. WSL memory: with the default 50 % (23.3 GiB) the Original's resident mode (fixed) left 2.2 GB available. A + `%UserProfile%\.wslconfig` with `[wsl2] memory=40GB swap=8GB` would let the complement grow toward ~30 GiB of + the 38 GiB the GPU does not hold. Needs `wsl --shutdown`; not applied. +4. The Original's `available_memory_bytes()` hybrid-cgroup bug (WSL2) is worth an upstream-style fix in the fork; + this branch does not modify `engine/strata`. +5. Native Windows would give the Original the full 47 GiB and its Windows paths (PrefetchVirtualMemory, + working-set trimming); it needs a Windows CUDA toolkit install (not present), so it was not tried. +6. Statistics: n = 6 per arm (2 passes x 3 prompts), single process per arm, uncontrolled page-cache state; the + charter's paired-A/B requirements (>= 30 repeats, CIs) are not met. Treat the ratios as indicative.