forked from brontoguana/krasis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdev
More file actions
executable file
·4372 lines (4116 loc) · 196 KB
/
Copy pathdev
File metadata and controls
executable file
·4372 lines (4116 loc) · 196 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
#
# Krasis dev helper — single entry point for build, run, test, benchmark.
#
# Usage:
# ./dev build Rebuild Rust extension into this repo only
# ./dev build-sidecars Build Marlin/FlashAttention package sidecars
# ./dev verify-sidecars Verify package sidecar manifest and hashes
# ./dev sidecar-key Print Marlin/FlashAttention sidecar bundle key
# ./dev pack-sidecar-bundle Pack verified sidecars into target/sidecars/bundles
# ./dev restore-sidecar-bundle Restore sidecars from local/GitHub bundle cache
# ./dev upload-sidecar-bundle Upload verified sidecar bundle to configured release
# ./dev run <config> Launch server from a test config
# ./dev run <config> --benchmark Launch with benchmark, then serve
# ./dev launcher-run <config> Launch through the primary launcher path
# ./dev test <config> Run short model test (benchmark + network tests)
# ./dev test <config> --thorough Run thorough model test (stress + benchmark + network + large)
# ./dev network <port> Run network tests against a running server
# ./dev network <port> --large Include large-prompt tests
# ./dev benchmark <config> Run standard benchmark (prefill/decode/round trip) and exit
# ./dev approved-heatmap-build <config> --out <path>
# Build approved cumulative HCS route heatmap checkpoints and exit
# Add --resume-from <json> to append prompts to an existing artifact
# ./dev approved-heatmap-eval <config> <heatmap.json>
# Benchmark a config with an approved heatmap artifact
# ./dev checkpoint-identity-test Test unified checkpoint/cache/heatmap identity
# ./dev approved-heatmap-migrate <audit|migrate|verify> [--dry-run]
# Audit/migrate dual-key online heatmaps
# ./dev speed-test Run the fixed standard speed benchmark (QCN INT4 HQQ4 k4v4)
# ./dev perplexity <config> Run perplexity eval (WikiText-2 by default) and exit
# ./dev quality-ppl <config> Measure PPL through a running Rust prefill test endpoint
# ./dev release-test <model> Run full release test (launcher matrix + release config matrix, produces report)
# ./dev release-test-all [target] Run release test on all supported models sequentially
# If a target name is given (e.g. "rc8"), progress is saved
# to a state file. Re-running with the same target resumes
# from the first non-passed model. Without a target, runs
# all models with no resume capability.
# ./dev launcher-test Validate launcher config serialization and server startup parsing
# ./dev windows-launcher-test Build and test the native Windows launcher logic
# ./dev server-test Test Rust HTTP/template and reference-verdict contracts
# ./dev manager-test Test Rust Manager/API and launcher schema contracts
# ./dev reference-test <config> Compare against stored non-HF references; HF artifacts require override
# ./dev reference-test --compare <model> Comparison matrix; HF artifacts require override
# ./dev reference-inventory Inventory stored reference artifacts and classify contract state
# ./dev witness-inputs <model> Build stored input_token_ids from fixed prompt-source JSON
# ./dev witness-model-check <model> Check expected BF16 GGUF witness model readiness
# ./dev witness-build Build the pinned llama-witness validator
# ./dev witness-gguf-preflight <model> Preflight BF16 GGUF witness conversion readiness
# ./dev witness-gguf-convert <model> Convert local safetensors to BF16 GGUF after preflight
# ./dev witness-capture <model> Capture llama-witness JSON from stored input_token_ids
# ./dev witness-compare <config> Compare Krasis against llama-witness JSON
# ./dev hqq-attn-diff <model> Offline HQQ attention artifact diff against BF16 source
# ./dev hqq-self-calibrate <config> Capture self-calibration evidence / candidates only
# ./dev hqq-gpu-search-probe Prototype GPU HQQ candidate-search timing/quality
# ./dev expert-hqq-cache-generate <manifest.json> Generate KRHQ cache from explicit manifest
# ./dev tileq-build <subcommand> Plan/build/verify source-bound KTQ1 expert caches
# ./dev expert-hqq-trace-compare <trace.json> <spec.json> <metrics.tsv> Compare diagnostic HQQ trace export offline
# ./dev capture-box <subcommand> ARCHIVED HF capture wrapper; requires explicit override
# ./dev capture-preflight ARCHIVED HF capture host preflight; requires explicit override
# ./dev reference-prep <model> ARCHIVED HF dependency/model prep; requires explicit override
# ./dev generate-reference <model> ARCHIVED HF reference capture; requires explicit override
# ./dev trace-diff <expected> <actual> Diff two KRASIS_TRACE logs offline
# ./dev awq-calibrate <config> Deprecated AWQ calibration command (disabled)
# ./dev test-kernels [name] Run CUDA kernel unit tests (or filter by name)
# ./dev cpu-tail-calibrate <config> [options]
# Optimize/measure CPU-tail under live GPU DMA
# ./dev chat [args] Run krasis chat from source
# ./dev sanity Run sanity test prompts against running server
# ./dev kill Kill all krasis processes and free GPU memory
# ./dev install Sync krasis command to ~/.local/bin (uses source)
# ./dev shell Drop into a Python shell bound to this repo
# ./dev python <args...> Run arbitrary Python bound to this repo
# ./dev verify-imports Verify imports resolve inside this repo
#
# Timing / profiling:
# Add --timing to any command to enable per-component decode timing.
# This inserts GPU synchronization barriers between each decode phase and
# prints a detailed timing breakdown at the end. Adds ~30-50% overhead so
# do NOT use for speed benchmarks — only for understanding where time goes.
#
# Examples:
# ./dev benchmark qcn --timing Profile decode components
# ./dev run qcn --timing Run server with timing enabled
# ./dev benchmark qcn Normal speed benchmark (no timing overhead)
#
# Debug tracing:
# KRASIS_TRACE=1 enables structured decode tracing with zero normal-mode cost.
# Optional filters:
# KRASIS_TRACE_STEPS=0-1
# KRASIS_TRACE_LAYERS=0-3
# KRASIS_TRACE_COMPONENTS=embedding,gqa,moe,final
# KRASIS_TRACE_VALUES=8
# KRASIS_TRACE_ELEMS=2048
# KRASIS_TRACE_DUMP_DIR=/tmp/krasis-trace
# KRASIS_TRACE_PY_COMPARE=1 # one first-step compare via built test endpoint during validate
#
# Configs are short names that map to validated configs:
# qcn -> tests/qcn-k4v4-hqq4-int4-benchmark.conf
# dsv4 -> tests/deepseek-v4-flash-0731-hqq8.conf
# gemma -> tests/gemma-4-4-a16.conf
#
set -euo pipefail
# ── Environment ──────────────────────────────────────────────────────
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
infer_repo_home() {
local path="$1"
case "$path" in
/home/*/*)
local remainder="${path#/home/}"
local user="${remainder%%/*}"
[[ -n "$user" ]] && echo "/home/$user"
;;
/Users/*/*)
local remainder="${path#/Users/}"
local user="${remainder%%/*}"
[[ -n "$user" ]] && echo "/Users/$user"
;;
*)
return 1
;;
esac
}
REFERENCE_CAPTURE_ROOT_SOURCE="home"
if [[ -n "${KRASIS_REFERENCE_CAPTURE_ROOT:-}" ]]; then
REFERENCE_CAPTURE_ROOT="${KRASIS_REFERENCE_CAPTURE_ROOT}"
REFERENCE_CAPTURE_ROOT_SOURCE="env"
elif REPO_HOME="$(infer_repo_home "$SCRIPT_DIR")"; then
REFERENCE_CAPTURE_ROOT="${REPO_HOME}/.krasis"
REFERENCE_CAPTURE_ROOT_SOURCE="repo_home"
else
REFERENCE_CAPTURE_ROOT="${HOME}/.krasis"
fi
PYTHON="${KRASIS_DEV_PYTHON:-/home/main/miniconda3/envs/ktransformers/bin/python}"
export PYTHONUNBUFFERED=1
# WSL2: add CUDA driver path so Rust cudarc can find libcuda.so
[[ -d /usr/lib/wsl/lib ]] && export LD_LIBRARY_PATH="/usr/lib/wsl/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
PIP="${KRASIS_DEV_PIP:-/home/main/miniconda3/envs/ktransformers/bin/pip}"
MATURIN="${KRASIS_DEV_MATURIN:-/home/main/.local/bin/maturin}"
SO_FILE="$SCRIPT_DIR/python/krasis/krasis.cpython-311-x86_64-linux-gnu.so"
WHEEL_DIR="$SCRIPT_DIR/target/dev-wheels"
REPO_PYTHONPATH="$SCRIPT_DIR/python"
REPO_LIBPATH="$SCRIPT_DIR/python/krasis.libs"
STANDARD_SPEED_TEST_CONFIG="$SCRIPT_DIR/tests/qcn-k4v4-hqq4-int4-benchmark.conf"
REFERENCE_CAPTURE_MODELS_DIR="${REFERENCE_CAPTURE_ROOT}/models"
REFERENCE_CAPTURE_VENV="${REFERENCE_CAPTURE_ROOT}/reference-capture-venv"
REFERENCE_CAPTURE_READY_JSON="${REFERENCE_CAPTURE_ROOT}/capture-host-ready.json"
REFERENCE_CAPTURE_READY_STAMP="${REFERENCE_CAPTURE_ROOT}/capture-host-ready.stamp"
WITNESS_REPO="${KRASIS_LLAMA_WITNESS_REPO:-$SCRIPT_DIR/../krasis-llama-witness}"
WITNESS_PROFILE_ID="${KRASIS_WITNESS_PROFILE_ID:-llama_witness_first_token}"
RED="\033[0;31m"
GREEN="\033[0;32m"
YELLOW="\033[1;33m"
CYAN="\033[0;36m"
BOLD="\033[1m"
NC="\033[0m"
info() { echo -e "${CYAN}${BOLD}=>${NC} $*"; }
ok() { echo -e "${GREEN}${BOLD}OK${NC} $*"; }
warn() { echo -e "${YELLOW}${BOLD}!!${NC} $*"; }
err() { echo -e "${RED}${BOLD}ERROR${NC} $*" >&2; exit 1; }
build_timer_start() {
date +%s
}
build_timer_end() {
local label="$1"
local start="$2"
local status="${3:-0}"
local end
end=$(date +%s)
echo "KRASIS_BUILD_TIMING phase=\"$label\" status=$status duration_s=$((end - start))"
}
require_archived_hf_reference_override() {
local command="$1"
if [[ "${KRASIS_ALLOW_ARCHIVED_HF_REFERENCE:-}" != "1" ]]; then
err "$command is archived. HF/Transformers reference tooling and artifacts are no longer a trusted witness path for Qwen3.5/large-model HQQ work. Use llama-witness for new reference authority. To rerun archived HF tooling for forensic evidence only, set KRASIS_ALLOW_ARCHIVED_HF_REFERENCE=1 and document the reason in krasis-internal."
fi
warn "$command is archived; running only because KRASIS_ALLOW_ARCHIVED_HF_REFERENCE=1 is set."
}
build_base_ld_library_path() {
local current="${LD_LIBRARY_PATH:-}"
local preferred=""
# Some container images expose CUDA compat stubs that can override the real
# host driver and trigger cuda error 803. When both exist, prefer the host
# driver directories explicitly.
if [[ -f /usr/lib/x86_64-linux-gnu/libcuda.so.1 ]] && compgen -G "/usr/local/cuda*/compat/libcuda.so*" >/dev/null; then
preferred="/usr/lib/x86_64-linux-gnu:/lib/x86_64-linux-gnu"
fi
if [[ -n "$preferred" ]]; then
echo "$preferred${current:+:$current}"
else
echo "$current"
fi
}
create_run_dir() {
local run_type="$1"
local ts dir counter=1
mkdir -p "$SCRIPT_DIR/logs"
ts=$(date +%Y%m%d_%H%M%S)
dir="$SCRIPT_DIR/logs/${run_type}_${ts}"
while [[ -e "$dir" ]]; do
dir="$SCRIPT_DIR/logs/${run_type}_${ts}_$counter"
counter=$((counter + 1))
done
mkdir -p "$dir"
echo "$dir"
}
# ── Sanity checks ────────────────────────────────────────────────────
[[ -f "$PYTHON" ]] || err "Python not found at $PYTHON
See DEV.md for environment setup instructions."
[[ -f "$MATURIN" ]] || err "maturin not found at $MATURIN
Install: pip install maturin"
# ── Config resolver ──────────────────────────────────────────────────
resolve_config() {
local name="$1"
case "$name" in
qcn|QCN) echo "$SCRIPT_DIR/tests/qcn-k4v4-hqq4-int4-benchmark.conf" ;;
dsv4|deepseek-v4|deepseek-v4-flash|dsv4-0731|deepseek-v4-0731|deepseek-v4-flash-0731)
echo "$SCRIPT_DIR/tests/deepseek-v4-flash-0731-hqq8.conf" ;;
gemma|Gemma) echo "$SCRIPT_DIR/tests/gemma-4-4-a16.conf" ;;
*)
# Try as a direct path
if [[ -f "$name" ]]; then
echo "$name"
elif [[ -f "$SCRIPT_DIR/testconfigs/$name" ]]; then
echo "$SCRIPT_DIR/testconfigs/$name"
elif [[ -f "$SCRIPT_DIR/tests/$name" ]]; then
echo "$SCRIPT_DIR/tests/$name"
else
err "Unknown config: $name
Available: qcn, dsv4, gemma
Or pass a path to a .conf file."
fi
;;
esac
}
resolve_model_name() {
case "$1" in
qcn|QCN|qwen3-coder-next|Qwen3-Coder-Next) echo "Qwen3-Coder-Next" ;;
q122b|Q122B|Qwen3.5-122B-A10B) echo "Qwen3.5-122B-A10B" ;;
dsv4|deepseek-v4|deepseek-v4-flash|dsv4-0731|deepseek-v4-0731|deepseek-v4-flash-0731) echo "DeepSeek-V4-Flash-0731" ;;
*) echo "$1" ;;
esac
}
# No need for conf_to_args — server.py has native --config support
# Extract port from a .conf file
conf_port() {
local conf="$1"
grep '^CFG_PORT=' "$conf" | head -1 | cut -d'"' -f2
}
# ── Auto-rebuild check ──────────────────────────────────────────────
needs_rebuild() {
# If .so doesn't exist, definitely need to build
[[ ! -f "$SO_FILE" ]] && return 0
local so_mtime
so_mtime=$(stat --format="%Y" "$SO_FILE" 2>/dev/null) || return 0
# Check if any Rust source or Cargo files are newer than the .so
while IFS= read -r -d '' f; do
local f_mtime
f_mtime=$(stat --format="%Y" "$f" 2>/dev/null) || continue
if [[ "$f_mtime" -gt "$so_mtime" ]]; then
return 0
fi
done < <(find "$SCRIPT_DIR/src" -name "*.rs" -print0 2>/dev/null)
# Check Cargo.toml and build.rs
for f in "$SCRIPT_DIR/Cargo.toml" "$SCRIPT_DIR/build.rs"; do
if [[ -f "$f" ]]; then
local f_mtime
f_mtime=$(stat --format="%Y" "$f" 2>/dev/null) || continue
if [[ "$f_mtime" -gt "$so_mtime" ]]; then
return 0
fi
fi
done
return 1
}
auto_rebuild() {
if needs_rebuild; then
warn "Rust source is newer than compiled extension. Rebuilding..."
do_build
fi
}
run_repo_python() {
local ld_path
ld_path="$(build_base_ld_library_path)"
if [[ -d "$REPO_LIBPATH" ]]; then
ld_path="$REPO_LIBPATH${ld_path:+:$ld_path}"
fi
PYTHONNOUSERSITE=1 PYTHONPATH="$REPO_PYTHONPATH${PYTHONPATH:+:$PYTHONPATH}" LD_LIBRARY_PATH="$ld_path" "$PYTHON" "$@"
}
exec_repo_python() {
local ld_path
ld_path="$(build_base_ld_library_path)"
if [[ -d "$REPO_LIBPATH" ]]; then
ld_path="$REPO_LIBPATH${ld_path:+:$ld_path}"
fi
exec env PYTHONNOUSERSITE=1 PYTHONPATH="$REPO_PYTHONPATH${PYTHONPATH:+:$PYTHONPATH}" LD_LIBRARY_PATH="$ld_path" "$PYTHON" "$@"
}
reference_capture_python_bin() {
local capture_python="$REFERENCE_CAPTURE_VENV/bin/python"
if [[ -x "$capture_python" ]]; then
echo "$capture_python"
else
echo "$PYTHON"
fi
}
run_reference_capture_python() {
local ld_path python_bin
python_bin="$(reference_capture_python_bin)"
ld_path="$(build_base_ld_library_path)"
if [[ -d "$REPO_LIBPATH" ]]; then
ld_path="$REPO_LIBPATH${ld_path:+:$ld_path}"
fi
PYTHONNOUSERSITE=1 PYTHONPATH="$REPO_PYTHONPATH${PYTHONPATH:+:$PYTHONPATH}" LD_LIBRARY_PATH="$ld_path" "$python_bin" "$@"
}
print_capture_box_env() {
info "Capture-box environment"
echo "repo_root=$SCRIPT_DIR"
echo "repo_home=$1"
echo "HOME=$HOME"
echo "PATH=$PATH"
echo "capture_root=$REFERENCE_CAPTURE_ROOT"
echo "capture_root_source=$REFERENCE_CAPTURE_ROOT_SOURCE"
echo "capture_models_dir=$REFERENCE_CAPTURE_MODELS_DIR"
echo "capture_venv=$REFERENCE_CAPTURE_VENV"
echo "ready_json=$REFERENCE_CAPTURE_READY_JSON"
echo "ready_stamp=$REFERENCE_CAPTURE_READY_STAMP"
}
enter_capture_box_env() {
local repo_home
repo_home="$(infer_repo_home "$SCRIPT_DIR" || true)"
[[ -n "$repo_home" ]] || err "Cannot derive a stable user home from repo path $SCRIPT_DIR.
Run from a checkout under /home/<user>/... or /Users/<user>/..., or set KRASIS_REFERENCE_CAPTURE_ROOT explicitly."
export HOME="$repo_home"
export PATH="$repo_home/.cargo/bin:$PATH"
export KRASIS_CAPTURE_BOX_ACTIVE=1
export KRASIS_CAPTURE_BOX_REPO_HOME="$repo_home"
export KRASIS_REFERENCE_CAPTURE_ROOT="$repo_home/.krasis"
export KRASIS_REFERENCE_CAPTURE_ROOT_SOURCE="capture_box"
REFERENCE_CAPTURE_ROOT="$KRASIS_REFERENCE_CAPTURE_ROOT"
REFERENCE_CAPTURE_ROOT_SOURCE="$KRASIS_REFERENCE_CAPTURE_ROOT_SOURCE"
REFERENCE_CAPTURE_MODELS_DIR="${REFERENCE_CAPTURE_ROOT}/models"
REFERENCE_CAPTURE_VENV="${REFERENCE_CAPTURE_ROOT}/reference-capture-venv"
REFERENCE_CAPTURE_READY_JSON="${REFERENCE_CAPTURE_ROOT}/capture-host-ready.json"
REFERENCE_CAPTURE_READY_STAMP="${REFERENCE_CAPTURE_ROOT}/capture-host-ready.stamp"
export KRASIS_REFERENCE_CAPTURE_MODELS_DIR="$REFERENCE_CAPTURE_MODELS_DIR"
export KRASIS_REFERENCE_CAPTURE_VENV="$REFERENCE_CAPTURE_VENV"
export KRASIS_REFERENCE_CAPTURE_READY_JSON="$REFERENCE_CAPTURE_READY_JSON"
export KRASIS_REFERENCE_CAPTURE_READY_STAMP="$REFERENCE_CAPTURE_READY_STAMP"
if [[ ! "$SCRIPT_DIR" =~ ^"$repo_home"/ ]]; then
err "Repo path $SCRIPT_DIR is not inside the enforced capture-box home $repo_home."
fi
}
verify_repo_imports() {
local output
local ld_path
ld_path="$(build_base_ld_library_path)"
if [[ -d "$REPO_LIBPATH" ]]; then
ld_path="$REPO_LIBPATH${ld_path:+:$ld_path}"
fi
output=$(PYTHONNOUSERSITE=1 PYTHONPATH="$REPO_PYTHONPATH" LD_LIBRARY_PATH="$ld_path" SCRIPT_DIR="$SCRIPT_DIR" "$PYTHON" - <<'PY'
import importlib
import os
import pathlib
import sys
repo = pathlib.Path(os.environ["SCRIPT_DIR"]).resolve()
pkg = importlib.import_module("krasis")
ext = importlib.import_module("krasis.krasis")
pkg_path = pathlib.Path(pkg.__file__).resolve()
ext_path = pathlib.Path(ext.__file__).resolve()
def inside_repo(path: pathlib.Path) -> bool:
try:
path.relative_to(repo)
return True
except ValueError:
return False
print(f"krasis: {pkg_path}")
print(f"krasis.krasis: {ext_path}")
if not inside_repo(pkg_path) or not inside_repo(ext_path):
sys.exit(1)
PY
) || {
echo "$output"
err "Import verification failed: dev runtime is not bound to this repo."
}
info "Import origin check:"
echo "$output"
}
verify_repo_python_imports() {
local output
local ld_path
ld_path="$(build_base_ld_library_path)"
if [[ -d "$REPO_LIBPATH" ]]; then
ld_path="$REPO_LIBPATH${ld_path:+:$ld_path}"
fi
local python_bin
python_bin="$(reference_capture_python_bin)"
output=$(PYTHONNOUSERSITE=1 PYTHONPATH="$REPO_PYTHONPATH" LD_LIBRARY_PATH="$ld_path" SCRIPT_DIR="$SCRIPT_DIR" "$python_bin" - <<'PY'
import importlib
import os
import pathlib
import sys
repo = pathlib.Path(os.environ["SCRIPT_DIR"]).resolve()
pkg = importlib.import_module("krasis")
contract = importlib.import_module("tests.reference_contract")
pkg_path = pathlib.Path(pkg.__file__).resolve()
contract_path = pathlib.Path(contract.__file__).resolve()
capture_path = (repo / "tests" / "generate_reference.py").resolve()
def inside_repo(path: pathlib.Path) -> bool:
try:
path.relative_to(repo)
return True
except ValueError:
return False
print(f"krasis: {pkg_path}")
print(f"tests.reference_contract: {contract_path}")
print(f"tests.generate_reference: {capture_path}")
if not capture_path.is_file():
sys.exit(1)
if not inside_repo(pkg_path) or not inside_repo(contract_path) or not inside_repo(capture_path):
sys.exit(1)
PY
) || {
echo "$output"
err "Python import verification failed: HF capture runtime is not bound to this repo."
}
info "Reference capture python: $python_bin"
info "Python import origin check:"
echo "$output"
}
# ── GPU cleanup ─────────────────────────────────────────────────────
# Kill any existing krasis processes and wait for GPUs to be fully clear.
# Called before every run/test to prevent OOMs from stale processes.
cleanup_gpu() {
# Optional args: config file path and explicit selected-GPU override.
# If provided, only check GPUs listed in the effective selection.
local conf="${1:-}"
local selected_gpus="${2:-}"
if [[ -z "$selected_gpus" && -n "$conf" && -f "$conf" ]]; then
selected_gpus=$(grep '^CFG_SELECTED_GPUS=' "$conf" 2>/dev/null | head -1 | cut -d'"' -f2 || true)
fi
# Find krasis server/stress/benchmark Python processes (but not this script).
# When a config selects specific GPUs, only kill krasis processes currently
# using those GPUs so a separate Krasis runtime on another GPU can stay up.
local pids
pids=$(pgrep -f 'python.*krasis\.' 2>/dev/null || true)
if [[ -n "$pids" && -n "$selected_gpus" ]]; then
local selected_uuids=""
local gpu_idx gpu_uuid gpu_pci
while IFS=',' read -r gpu_idx gpu_uuid gpu_pci; do
gpu_idx="${gpu_idx//[[:space:]]/}"
gpu_uuid="${gpu_uuid//[[:space:]]/}"
gpu_pci="${gpu_pci//[[:space:]]/}"
for sg in $(echo "$selected_gpus" | tr ',' ' '); do
if [[ "$gpu_idx" == "$sg" || "$gpu_uuid" == "$sg" || "${gpu_pci,,}" == "${sg,,}" ]]; then
selected_uuids+="${gpu_uuid}"$'\n'
fi
done
done < <(nvidia-smi --query-gpu=index,uuid,pci.bus_id --format=csv,noheader,nounits 2>/dev/null || true)
local selected_gpu_pids=""
local app_pid app_uuid
while IFS=',' read -r app_pid app_uuid; do
app_pid="${app_pid//[[:space:]]/}"
app_uuid="${app_uuid//[[:space:]]/}"
[[ -z "$app_pid" || -z "$app_uuid" ]] && continue
if grep -qxF "$app_uuid" <<< "$selected_uuids"; then
selected_gpu_pids+="${app_pid}"$'\n'
fi
done < <(nvidia-smi --query-compute-apps=pid,gpu_uuid --format=csv,noheader,nounits 2>/dev/null || true)
local filtered_pids=""
local p
for p in $pids; do
if grep -qxF "$p" <<< "$selected_gpu_pids"; then
filtered_pids+="${p}"$'\n'
fi
done
pids="$filtered_pids"
fi
if [[ -n "$pids" ]]; then
warn "Found existing krasis processes — killing them:"
for p in $pids; do
local cmdline
cmdline=$(ps -p "$p" -o args= 2>/dev/null || echo "unknown")
warn " PID $p: $cmdline"
done
# SIGTERM first
for p in $pids; do
kill -TERM "$p" 2>/dev/null || true
done
# Wait up to 10s for graceful exit
local waited=0
while [[ $waited -lt 10 ]]; do
local still_alive=false
for p in $pids; do
if kill -0 "$p" 2>/dev/null; then
still_alive=true
break
fi
done
$still_alive || break
sleep 1
waited=$((waited + 1))
done
# SIGKILL any survivors
for p in $pids; do
if kill -0 "$p" 2>/dev/null; then
warn " PID $p still alive after SIGTERM, sending SIGKILL"
kill -9 "$p" 2>/dev/null || true
fi
done
# Wait for SIGKILL to take effect
sleep 2
for p in $pids; do
wait "$p" 2>/dev/null || true
done
fi
# Now wait for GPU memory to actually be released.
# CUDA memory isn't freed until the process fully exits.
if [[ -n "$selected_gpus" ]]; then
info "Waiting for selected GPUs ($selected_gpus) to clear..."
else
info "Waiting for GPU memory to clear..."
fi
local gpu_timeout=30
local gpu_waited=0
while [[ $gpu_waited -lt $gpu_timeout ]]; do
local all_clear=true
while IFS=', ' read -r idx gpu_uuid gpu_pci used gpu_mem_total; do
# If selected_gpus is set, only check those GPUs
if [[ -n "$selected_gpus" ]]; then
local check_this=false
for sg in $(echo "$selected_gpus" | tr ',' ' '); do
[[ "$idx" == "$sg" || "$gpu_uuid" == "$sg" || "${gpu_pci,,}" == "${sg,,}" ]] && check_this=true
done
$check_this || continue
fi
# Baseline is ~200-300 MiB (desktop compositor). 500 MiB threshold.
if [[ "$used" -gt 500 ]]; then
all_clear=false
break
fi
done < <(nvidia-smi --query-gpu=index,uuid,pci.bus_id,memory.used,memory.total --format=csv,noheader,nounits 2>/dev/null)
if $all_clear; then
if [[ -n "$selected_gpus" ]]; then
ok "Selected GPUs ($selected_gpus) clear."
else
ok "All GPUs clear."
fi
return 0
fi
sleep 1
gpu_waited=$((gpu_waited + 1))
done
# If we get here, GPUs didn't clear. Show what's using them.
warn "GPUs still not clear after ${gpu_timeout}s:"
nvidia-smi 2>/dev/null || true
err "Cannot proceed — GPU memory not released. Check for non-krasis processes using the GPU."
}
extract_selected_gpus_arg() {
local arg
while [[ $# -gt 0 ]]; do
arg="$1"
case "$arg" in
--selected-gpus=*)
printf '%s\n' "${arg#--selected-gpus=}"
return 0
;;
--selected-gpus)
if [[ $# -lt 2 ]]; then
err "--selected-gpus requires a comma-separated GPU list"
fi
printf '%s\n' "$2"
return 0
;;
esac
shift
done
return 0
}
resolve_config_cuda_visible_devices() {
local conf="$1"
local selected_gpus
selected_gpus=$(grep '^CFG_SELECTED_GPUS=' "$conf" 2>/dev/null | head -1 | cut -d'"' -f2 || true)
[[ -n "$selected_gpus" ]] || return 0
# Reuse the server's stable-selector contract (indices, UUIDs, PCI IDs,
# and unique name/memory aliases). This runs after auto_rebuild and in a
# short-lived setup process, before the actual evaluator imports CUDA.
run_repo_python -c \
'import sys; from krasis.server import _normalize_selected_gpus; print(_normalize_selected_gpus(sys.argv[1], "CFG_SELECTED_GPUS"))' \
"$selected_gpus"
}
# ── Commands ─────────────────────────────────────────────────────────
read_fla_sidecar_architectures() {
"$PYTHON" -c \
'import json, sys; data=json.load(open(sys.argv[1], encoding="utf-8")); print(*data["architectures"], sep="\n")' \
"$SCRIPT_DIR/python/krasis/fla_sidecar_contract.json"
}
do_build_fla() {
local phase_start
phase_start=$(build_timer_start)
# Cross-compile FLA (Flash Linear Attention) Triton kernels for all
# target GPU architectures. The resulting .so files are placed in
# python/krasis/ so maturin can include them in the wheel.
local fla_script="$SCRIPT_DIR/src/cuda/fla/compile_kernels.py"
local fla_src_dir="$SCRIPT_DIR/src/cuda/fla"
local dest="$SCRIPT_DIR/python/krasis"
local archs=()
mapfile -t archs < <(read_fla_sidecar_architectures)
[[ "${#archs[@]}" -gt 0 ]] || err "FLA sidecar contract has no architectures"
# Check if recompilation is needed: any .so missing or any source newer?
local needs_rebuild=false
for arch in "${archs[@]}"; do
if [[ ! -f "$dest/libkrasis_fla_sm${arch}.so" ]]; then
needs_rebuild=true
break
fi
done
if ! $needs_rebuild; then
# Check if any Python source in fla/ is newer than the oldest .so
local oldest_so_mtime
oldest_so_mtime=$(stat --format="%Y" "$dest"/libkrasis_fla_sm*.so 2>/dev/null | sort -n | head -1)
if [[ -n "$oldest_so_mtime" ]]; then
while IFS= read -r pyfile; do
local py_mtime
py_mtime=$(stat --format="%Y" "$pyfile" 2>/dev/null) || continue
if [[ "$py_mtime" -gt "$oldest_so_mtime" ]]; then
needs_rebuild=true
break
fi
done < <(find "$fla_src_dir" -name "*.py" -type f 2>/dev/null)
fi
fi
if ! $needs_rebuild; then
ok "FLA kernels up to date (skipping)"
build_timer_end "dev FLA kernels" "$phase_start" 0
return
fi
info "Compiling FLA kernels for GPU architectures: ${archs[*]/#/sm_}..."
local fla_output="/tmp/fla_build"
set +e
KRASIS_DEV_SCRIPT=1 "$PYTHON" "$fla_script" --output-dir "$fla_output" \
--arch "${archs[@]}"
local status=$?
set -e
build_timer_end "dev FLA kernels" "$phase_start" "$status"
[[ "$status" -eq 0 ]] || err "FLA kernel compilation failed"
mkdir -p "$dest"
local count=0
for so in "$fla_output"/libkrasis_fla_sm*.so; do
[[ -f "$so" ]] || continue
cp "$so" "$dest/"
count=$((count + 1))
done
ok "FLA kernels: $count architectures compiled"
}
do_build_fla_windows_sources() {
local phase_start
phase_start=$(build_timer_start)
local output_dir="$SCRIPT_DIR/target/windows-fla-sources"
local archs=()
mapfile -t archs < <(read_fla_sidecar_architectures)
[[ "${#archs[@]}" -gt 0 ]] || err "FLA sidecar contract has no architectures"
info "Generating portable Windows FLA sources for: ${archs[*]/#/sm_}..."
rm -rf "$output_dir"
set +e
KRASIS_DEV_SCRIPT=1 KRASIS_FLA_CROSS_COMPILE=1 KRASIS_FLA_REQUIRE_ALL_ARCHS=1 \
"$PYTHON" "$SCRIPT_DIR/src/cuda/fla/compile_kernels.py" \
--output-dir "$output_dir" \
--target-platform windows \
--arch "${archs[@]}"
local status=$?
set -e
build_timer_end "dev Windows FLA source generation" "$phase_start" "$status"
[[ "$status" -eq 0 ]] || err "Windows FLA source generation failed"
local count=0
local source
for source in "$output_dir"/krasis_fla_sm*.cu; do
[[ -f "$source" ]] || continue
count=$((count + 1))
done
[[ "$count" -eq "${#archs[@]}" ]] || \
err "Windows FLA source generation produced $count/${#archs[@]} architectures"
[[ -f "$output_dir/windows-fla-manifest.json" ]] || \
err "Windows FLA source generation omitted windows-fla-manifest.json"
local nvcc_bin
nvcc_bin=$(command -v nvcc 2>/dev/null || true)
if [[ -z "$nvcc_bin" && -n "${CUDA_HOME:-}" && -x "$CUDA_HOME/bin/nvcc" ]]; then
nvcc_bin="$CUDA_HOME/bin/nvcc"
fi
if [[ -z "$nvcc_bin" && -n "${CUDA_PATH:-}" && -x "$CUDA_PATH/bin/nvcc" ]]; then
nvcc_bin="$CUDA_PATH/bin/nvcc"
fi
if [[ -z "$nvcc_bin" ]]; then
nvcc_bin=$(find /usr/local -maxdepth 4 -path "*/bin/nvcc" -type f -print -quit 2>/dev/null || true)
fi
[[ -n "$nvcc_bin" && -x "$nvcc_bin" ]] || \
err "nvcc not found after Windows FLA source generation"
local arch
for arch in "${archs[@]}"; do
"$nvcc_bin" \
-c \
-std=c++17 \
-allow-unsupported-compiler \
-Xcompiler -fPIC \
"$output_dir/krasis_fla_sm${arch}.cu" \
-o "$output_dir/krasis_fla_sm${arch}.o" || \
err "Portable FLA wrapper compile check failed for sm_$arch"
done
ok "Windows FLA sources: $count architectures generated"
}
do_build_sidecars() {
local phase_start
phase_start=$(build_timer_start)
info "Building Marlin/FlashAttention sidecars..."
local args=(build)
if [[ "${1:-}" == "--force" ]]; then
args+=(--force)
fi
set +e
KRASIS_DEV_SCRIPT=1 "$PYTHON" "$SCRIPT_DIR/scripts/build_sidecars.py" "${args[@]}"
local status=$?
set -e
build_timer_end "dev Marlin/FlashAttention sidecars" "$phase_start" "$status"
[[ "$status" -eq 0 ]] || err "Marlin/FlashAttention sidecar build failed"
}
do_verify_sidecars() {
local phase_start
phase_start=$(build_timer_start)
info "Verifying Marlin/FlashAttention sidecars..."
set +e
KRASIS_DEV_SCRIPT=1 "$PYTHON" "$SCRIPT_DIR/scripts/build_sidecars.py" verify
local status=$?
set -e
build_timer_end "dev sidecar verification" "$phase_start" "$status"
[[ "$status" -eq 0 ]] || err "Marlin/FlashAttention sidecar verification failed"
}
do_sidecar_key() {
KRASIS_DEV_SCRIPT=1 "$PYTHON" "$SCRIPT_DIR/scripts/build_sidecars.py" bundle-key "$@"
}
do_pack_sidecar_bundle() {
local phase_start
phase_start=$(build_timer_start)
info "Packing Marlin/FlashAttention sidecar bundle..."
set +e
KRASIS_DEV_SCRIPT=1 "$PYTHON" "$SCRIPT_DIR/scripts/build_sidecars.py" pack-bundle
local status=$?
set -e
build_timer_end "dev sidecar bundle pack" "$phase_start" "$status"
[[ "$status" -eq 0 ]] || err "Marlin/FlashAttention sidecar bundle pack failed"
}
do_restore_sidecar_bundle() {
local phase_start
phase_start=$(build_timer_start)
info "Restoring Marlin/FlashAttention sidecar bundle..."
local args=(restore-bundle)
if [[ "${1:-}" == "--github" ]]; then
args+=(--github)
fi
set +e
KRASIS_DEV_SCRIPT=1 "$PYTHON" "$SCRIPT_DIR/scripts/build_sidecars.py" "${args[@]}"
local status=$?
set -e
build_timer_end "dev sidecar bundle restore" "$phase_start" "$status"
[[ "$status" -eq 0 ]] || return "$status"
}
do_upload_sidecar_bundle() {
local phase_start
phase_start=$(build_timer_start)
info "Uploading Marlin/FlashAttention sidecar bundle..."
set +e
KRASIS_DEV_SCRIPT=1 "$PYTHON" "$SCRIPT_DIR/scripts/build_sidecars.py" upload-bundle
local status=$?
set -e
build_timer_end "dev sidecar bundle upload" "$phase_start" "$status"
[[ "$status" -eq 0 ]] || err "Marlin/FlashAttention sidecar bundle upload failed"
}
do_build() {
local build_start
build_start=$(build_timer_start)
info "Building Rust extension (repo-local maturin build --release)..."
export LD_LIBRARY_PATH
LD_LIBRARY_PATH="$(build_base_ld_library_path)"
# Compile FLA kernels first so they're in python/krasis/ for maturin
do_build_fla
do_build_sidecars
do_verify_sidecars
cd "$SCRIPT_DIR"
mkdir -p "$WHEEL_DIR"
rm -f "$WHEEL_DIR"/krasis-*.whl
local maturin_start
maturin_start=$(build_timer_start)
set +e
PATH="$HOME/.cargo/bin:$(dirname "$PYTHON"):$PATH" \
"$MATURIN" build --release --skip-auditwheel --out "$WHEEL_DIR" 2>&1
local maturin_status=$?
set -e
build_timer_end "dev maturin build" "$maturin_start" "$maturin_status"
[[ "$maturin_status" -eq 0 ]] || return "$maturin_status"
local wheel
wheel=$(ls -t "$WHEEL_DIR"/krasis-*.whl 2>/dev/null | head -1)
[[ -n "$wheel" ]] || err "Build succeeded but no wheel was produced in $WHEEL_DIR"
"$PYTHON" - "$wheel" "$SCRIPT_DIR/python/krasis" "$SCRIPT_DIR/python/krasis.libs" <<'PY'
import pathlib
import shutil
import sys
import zipfile
wheel = pathlib.Path(sys.argv[1])
target = pathlib.Path(sys.argv[2])
lib_target = pathlib.Path(sys.argv[3])
target.mkdir(parents=True, exist_ok=True)
lib_target.mkdir(parents=True, exist_ok=True)
for pattern in ("krasis*.so", "krasis*.pyd", "lib*.so", "*.dylib", "*.dll"):
for path in target.glob(pattern):
path.unlink()
for pattern in ("*.so", "*.so.*", "*.dylib", "*.dll"):
for path in lib_target.glob(pattern):
path.unlink()
with zipfile.ZipFile(wheel) as zf:
ext_members = [
name for name in zf.namelist()
if name.startswith("krasis/") and name.endswith((".so", ".pyd", ".dll", ".dylib"))
]
lib_members = [
name for name in zf.namelist()
if name.startswith("krasis.libs/")
]
if not ext_members:
raise SystemExit("No compiled artifacts found in wheel")
for member in ext_members:
dest = target / pathlib.Path(member).name
with zf.open(member) as src, open(dest, "wb") as dst:
shutil.copyfileobj(src, dst)
print(dest)
for member in lib_members:
dest = lib_target / pathlib.Path(member).name
with zf.open(member) as src, open(dest, "wb") as dst:
shutil.copyfileobj(src, dst)
print(dest)
PY
ok "Build complete. Extension at: $SO_FILE"
verify_repo_imports
build_timer_end "dev build total" "$build_start" 0
}
do_run() {
[[ $# -lt 1 ]] && err "Usage: ./dev run <config> [--benchmark] [--selected-gpus GPU[,GPU...]] [extra args...]"
local conf
conf=$(resolve_config "$1")
shift
local selected_gpus_override
selected_gpus_override=$(extract_selected_gpus_arg "$@")
local run_dir
run_dir=$(create_run_dir "dev-run")
cleanup_gpu "$conf" "$selected_gpus_override"
auto_rebuild
info "Launching from: $conf"
if [[ -n "$selected_gpus_override" ]]; then
info "Selected GPU override: $selected_gpus_override"
fi
info "Run dir: $run_dir"
verify_repo_imports
export KRASIS_RUN_DIR="$run_dir"
export KRASIS_RUN_TYPE="dev-run"
exec_repo_python -m krasis.server --config "$conf" "$@"
}
do_launcher_run() {
[[ $# -lt 1 ]] && err "Usage: ./dev launcher-run <config> [--benchmark] [extra args...]"
local conf
conf=$(resolve_config "$1")
shift
local selected_gpus_override
selected_gpus_override=$(extract_selected_gpus_arg "$@")
local run_dir
run_dir=$(create_run_dir "dev-launcher-run")
cleanup_gpu "$conf" "$selected_gpus_override"
auto_rebuild
info "Launching through Krasis launcher from: $conf"
info "Run dir: $run_dir"
verify_repo_imports
export KRASIS_RUN_DIR="$run_dir"
export KRASIS_RUN_TYPE="dev-launcher-run"
exec_repo_python -m krasis.launcher --config "$conf" "$@"
}
do_test() {
[[ $# -lt 1 ]] && err "Usage: ./dev test <config> [--thorough]"
local conf
conf=$(resolve_config "$1")
local thorough=false
[[ "${2:-}" == "--thorough" ]] && thorough=true
cleanup_gpu "$conf"
auto_rebuild
local run_dir
run_dir=$(create_run_dir "dev-test")
local port
port=$(conf_port "$conf")
[[ -z "$port" ]] && port=8012
info "=== Short Model Test ==="
info "Config: $conf"
info "Port: $port"
info "Run dir: $run_dir"
# Step 1: Launch server with benchmark
info "Step 1: Launching server with --benchmark..."
local logfile
logfile="$run_dir/test_stdout.log"
info "Log: $logfile"
verify_repo_imports
KRASIS_RUN_DIR="$run_dir" KRASIS_RUN_TYPE="dev-test" run_repo_python -m krasis.server --config "$conf" --benchmark > >(tee "$logfile") 2>&1 &
local pid=$!
# Wait for benchmark to complete AND server to be ready.
# Must wait for BENCHMARK COMPLETE, not just "Server ready", because
# the benchmark runs on a separate thread. Sending HTTP requests while
# the benchmark is still using the GPU causes CUDA_ERROR_ILLEGAL_ADDRESS.
local ready=false
local timeout=1200 # 20 minutes for model load + benchmark
local elapsed=0
while kill -0 "$pid" 2>/dev/null && [[ $elapsed -lt $timeout ]]; do