-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathdev
More file actions
executable file
·1657 lines (1523 loc) · 67.9 KB
/
dev
File metadata and controls
executable file
·1657 lines (1523 loc) · 67.9 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 run <config> Launch server from a test config
# ./dev run <config> --benchmark Launch with benchmark, then serve
# ./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 speed-test Run the fixed standard speed benchmark (QCN INT4 AWQ Polar4)
# ./dev perplexity <config> Run perplexity eval (WikiText-2 by default) and exit
# ./dev release-test <model> Run full release test (4 configs, 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 reference-test <config> Compare engine output against BF16 reference data
# ./dev reference-test --compare <model> Run 4 quant configs, produce comparative report
# ./dev reference-inventory Inventory stored reference artifacts and classify contract state
# ./dev capture-box <subcommand> Run HF capture commands through the strict paid-box wrapper
# ./dev capture-preflight Verify or bootstrap a host for HF reference capture
# ./dev reference-prep <model> Prepare HF capture deps and download a public model
# ./dev generate-reference <model> Generate a BF16 HF reference capture
# ./dev trace-diff <expected> <actual> Diff two KRASIS_TRACE logs offline
# ./dev awq-calibrate <config> Run AWQ calibration, produce attention template
# ./dev test-kernels [name] Run CUDA kernel unit tests (or filter by name)
# ./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 testconfigs/*.conf:
# qcn -> testconfigs/qcn-4-4-a16.conf
# qcn-a4 -> testconfigs/qcn-4-4-awq.conf
# q235 -> testconfigs/q235-4-4-a16.conf
# q235-a4 -> testconfigs/q235-4-4-awq.conf
# v2lite -> testconfigs/v2lite-4-4-a16.conf
# deepseek-vl -> testconfigs/deepseek-vl2-4-4-a16.conf
# qwen35 -> testconfigs/qwen35-4-4-a16.conf
# qwen35-a4 -> testconfigs/qwen35-4-4-awq.conf
# gemma -> tests/gemma-4-4-a16.conf
# minimax -> tests/minimax-m2-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="/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="/home/main/miniconda3/envs/ktransformers/bin/pip"
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-polar4-awq.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"
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_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/testconfigs/qcn-4-4-a16.conf" ;;
qcn-a4) echo "$SCRIPT_DIR/testconfigs/qcn-4-4-awq.conf" ;;
q235) echo "$SCRIPT_DIR/testconfigs/q235-4-4-a16.conf" ;;
q235-a4) echo "$SCRIPT_DIR/testconfigs/q235-4-4-awq.conf" ;;
v2lite|V2-Lite) echo "$SCRIPT_DIR/testconfigs/v2lite-4-4-a16.conf" ;;
deepseek-vl|vl2) echo "$SCRIPT_DIR/testconfigs/deepseek-vl2-4-4-a16.conf" ;;
qwen35|Qwen3.5) echo "$SCRIPT_DIR/testconfigs/qwen35-4-4-a16.conf" ;;
qwen35-a4) echo "$SCRIPT_DIR/testconfigs/qwen35-4-4-awq.conf" ;;
gemma|Gemma) echo "$SCRIPT_DIR/tests/gemma-4-4-a16.conf" ;;
minimax|MiniMax) echo "$SCRIPT_DIR/tests/minimax-m2-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, qcn-a4, q235, q235-a4, v2lite, deepseek-vl, qwen35, qwen35-a4, gemma, minimax
Or pass a path to a .conf file."
fi
;;
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 arg: config file path. If provided, only check GPUs listed in CFG_SELECTED_GPUS.
local conf="${1:-}"
local selected_gpus=""
if [[ -n "$conf" && -f "$conf" ]]; then
selected_gpus=$(grep '^CFG_SELECTED_GPUS=' "$conf" 2>/dev/null | head -1 | cut -d'"' -f2 || true)
fi
# Find all krasis server/stress/benchmark Python processes (but not this script)
local pids
pids=$(pgrep -f 'python.*krasis\.' 2>/dev/null || true)
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 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" ]] && 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,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."
}
# ── Commands ─────────────────────────────────────────────────────────
do_build_fla() {
# 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=(80 89 90 120)
# 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)"
return
fi
info "Compiling FLA kernels for GPU architectures: ${archs[*]/#/sm_}..."
local fla_output="/tmp/fla_build"
KRASIS_DEV_SCRIPT=1 "$PYTHON" "$fla_script" --output-dir "$fla_output" \
--arch "${archs[@]}" || 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() {
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
cd "$SCRIPT_DIR"
mkdir -p "$WHEEL_DIR"
rm -f "$WHEEL_DIR"/krasis-*.whl
PATH="$HOME/.cargo/bin:$(dirname "$PYTHON"):$PATH" \
"$MATURIN" build --release --skip-auditwheel --out "$WHEEL_DIR" 2>&1
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
}
do_run() {
[[ $# -lt 1 ]] && err "Usage: ./dev run <config> [--benchmark] [extra args...]"
local conf
conf=$(resolve_config "$1")
shift
local run_dir
run_dir=$(create_run_dir "dev-run")
cleanup_gpu "$conf"
auto_rebuild
info "Launching from: $conf"
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_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
if grep -q "BENCHMARK COMPLETE" "$logfile" 2>/dev/null; then
ready=true
break
fi
sleep 2
elapsed=$((elapsed + 2))
done
if ! $ready; then
if kill -0 "$pid" 2>/dev/null; then
warn "Timed out waiting for server (${timeout}s). Killing..."
kill -TERM "$pid" 2>/dev/null || true
sleep 2
kill -9 "$pid" 2>/dev/null || true
fi
err "Server did not start. Check log: $logfile"
fi
ok "Server is ready. Benchmark results are in the log."
# Step 2: Run network multi-prompt tests
info "Step 2: Running network multi-prompt tests..."
if $thorough; then
run_repo_python "$SCRIPT_DIR/tests/test_network.py" --port "$port" --large 2>&1 | tee -a "$logfile"
else
run_repo_python "$SCRIPT_DIR/tests/test_network.py" --port "$port" 2>&1 | tee -a "$logfile"
fi
local net_result=$?
# Cleanup: kill the server
info "Stopping server..."
kill -TERM "$pid" 2>/dev/null || true
sleep 2
kill -9 "$pid" 2>/dev/null || true
wait "$pid" 2>/dev/null || true
echo ""
if [[ $net_result -eq 0 ]]; then
ok "=== All tests PASSED ==="
else
err "Network tests FAILED (exit code $net_result)"
fi
info "Full log: $logfile"
}
do_release_test() {
[[ $# -lt 1 ]] && err "Usage: ./dev release-test <model> [--force-rebuild-cache]
model = directory name under ~/.krasis/models/
Example: ./dev release-test Qwen3-Coder-Next"
local model="$1"
shift
cleanup_gpu
local run_dir
run_dir=$(create_run_dir "release-test")
info "Starting release test for model: $model"
info "Run dir: $run_dir"
verify_repo_imports
KRASIS_DEV_SCRIPT=1 KRASIS_RUN_DIR="$run_dir" KRASIS_RUN_TYPE="release-test" run_repo_python "$SCRIPT_DIR/tests/release_test.py" "$model" "$@"
}
do_release_test_all() {
local SESSION_WS="Release Test"
local release_target="${1:-}"
local MODELS=(
"Qwen3-Coder-Next"
"Qwen3.5-35B-A3B"
"Qwen3.5-122B-A10B"
"Qwen3-235B-A22B"
"Qwen3.5-397B-A17B"
)
local total=${#MODELS[@]}
local completed=0
local skipped=0
local failed_model=""
local resuming=false
local state_file=""
local start_time
start_time=$(date +%s)
# State file for resume support (only when release target is given)
if [[ -n "$release_target" ]]; then
local state_dir="$SCRIPT_DIR/logs/release-tests"
mkdir -p "$state_dir"
state_file="$state_dir/release-all-${release_target}.state"
if [[ -f "$state_file" ]]; then
resuming=true
# Count previously passed models
for model in "${MODELS[@]}"; do
local status
status=$(grep "^${model}:" "$state_file" 2>/dev/null | cut -d: -f2) || true
if [[ "$status" == "PASSED" ]]; then
skipped=$((skipped + 1))
completed=$((completed + 1))
fi
done
if [[ $skipped -eq $total ]]; then
ok "All models already passed for release target '$release_target'. Nothing to do."
session-send "$SESSION_WS" "release-test-all '$release_target': all $total models already passed. Nothing to do." 2>/dev/null || true
return 0
fi
info "=== Resuming Release Test All: $release_target ==="
info "Previously passed: $skipped/$total"
else
info "=== Release Test All: $release_target ==="
# Create initial state file
for model in "${MODELS[@]}"; do
echo "${model}:PENDING" >> "$state_file"
done
fi
else
info "=== Release Test All ==="
fi
info "Models: ${MODELS[*]}"
info "Total: $total"
# Verify all models exist before starting
for model in "${MODELS[@]}"; do
local model_dir="$HOME/.krasis/models/$model"
if [[ ! -d "$model_dir" ]]; then
local msg="FAILED: Model $model not found at $model_dir. Cannot run release-test-all."
err "$msg"
fi
done
# Session start message
if $resuming; then
session-send "$SESSION_WS" "Resuming release-test-all '$release_target': $skipped/$total already passed, $(( total - skipped )) remaining.
Models: $(printf '%s, ' "${MODELS[@]}" | sed 's/, $//')" 2>/dev/null || warn "Could not send Session message"
else
local target_info=""
[[ -n "$release_target" ]] && target_info=" ($release_target)"
session-send "$SESSION_WS" "Starting release-test-all${target_info}: $total models to test.
Models: $(printf '%s, ' "${MODELS[@]}" | sed 's/, $//')" 2>/dev/null || warn "Could not send Session message"
fi
for model in "${MODELS[@]}"; do
# Skip already-passed models on resume
if [[ -n "$state_file" && -f "$state_file" ]]; then
local prev_status
prev_status=$(grep "^${model}:" "$state_file" 2>/dev/null | cut -d: -f2) || true
if [[ "$prev_status" == "PASSED" ]]; then
info "=== Skipping $model (already passed) ==="
continue
fi
fi
local idx=$((completed + 1))
info "=== [$idx/$total] Starting: $model ==="
session-send "$SESSION_WS" "[$idx/$total] Starting release test: $model" 2>/dev/null || true
local model_start
model_start=$(date +%s)
# Run release test — cleanup_gpu is called inside do_release_test
if do_release_test "$model"; then
completed=$((completed + 1))
local model_elapsed=$(( $(date +%s) - model_start ))
local model_mins=$((model_elapsed / 60))
local model_secs=$((model_elapsed % 60))
ok "[$completed/$total] PASSED: $model (${model_mins}m ${model_secs}s)"
session-send "$SESSION_WS" "[$completed/$total] PASSED: $model (${model_mins}m ${model_secs}s)" 2>/dev/null || true
# Update state file
if [[ -n "$state_file" ]]; then
sed -i "s/^${model}:.*/${model}:PASSED/" "$state_file"
fi
else
failed_model="$model"
local model_elapsed=$(( $(date +%s) - model_start ))
local model_mins=$((model_elapsed / 60))
local model_secs=$((model_elapsed % 60))
local msg="FAILED: $model (${model_mins}m ${model_secs}s). Stopping. $completed/$total models completed."
warn "$msg"
session-send "$SESSION_WS" "$msg" 2>/dev/null || true
# Update state file
if [[ -n "$state_file" ]]; then
sed -i "s/^${model}:.*/${model}:FAILED/" "$state_file"
fi
err "Release test failed on $model. Aborting."
fi
done
local configs_elapsed=$(( $(date +%s) - start_time ))
local configs_mins=$((configs_elapsed / 60))
local configs_secs=$((configs_elapsed % 60))
local target_suffix=""
[[ -n "$release_target" ]] && target_suffix=" ($release_target)"
local configs_msg="All configs passed: $completed/$total models in ${configs_mins}m ${configs_secs}s. Starting perplexity phase.${target_suffix}"
ok "$configs_msg"
session-send "$SESSION_WS" "$configs_msg" 2>/dev/null || true
# ── Perplexity phase: one INT4/AWQ pass per model ──────────────
info "=== Perplexity Phase: INT4/AWQ for all models ==="
session-send "$SESSION_WS" "Starting perplexity phase: INT4/AWQ for $total models" 2>/dev/null || true
local ppl_passed=0
local ppl_failed=0
local best_gpu_idx
best_gpu_idx=$(nvidia-smi --query-gpu=index,memory.total --format=csv,noheader,nounits | sort -t',' -k2 -nr | head -1 | cut -d',' -f1 | tr -d ' ')
for model in "${MODELS[@]}"; do
local model_dir="$HOME/.krasis/models/$model"
local config_json="$model_dir/config.json"
if [[ ! -f "$config_json" ]]; then
warn "No config.json for $model — skipping perplexity"
ppl_failed=$((ppl_failed + 1))
session-send "$SESSION_WS" "[PPL] SKIP: $model (no config.json)" 2>/dev/null || true
continue
fi
# Get num_layers from model config
local num_layers
num_layers=$("$PYTHON" -c "
import json, sys
c = json.load(open('$config_json'))
tc = c.get('text_config', c)
print(tc.get('num_hidden_layers', 0))
") || num_layers=0
if [[ "$num_layers" -eq 0 ]]; then
warn "Could not detect num_layers for $model — skipping perplexity"
ppl_failed=$((ppl_failed + 1))
session-send "$SESSION_WS" "[PPL] SKIP: $model (unknown layers)" 2>/dev/null || true
continue
fi
# Generate temp INT4/AWQ config
local ppl_conf
ppl_conf=$(mktemp /tmp/krasis-ppl-XXXXXX.conf)
cat > "$ppl_conf" <<PPLCONF
# Perplexity config — INT4/INT4 AWQ — $model
MODEL_PATH="$model_dir"
CFG_SELECTED_GPUS="$best_gpu_idx"
CFG_PP_PARTITION="$num_layers"
CFG_LAYER_GROUP_SIZE="2"
CFG_KV_DTYPE="fp8_e4m3"
CFG_GPU_EXPERT_BITS="4"
CFG_CPU_EXPERT_BITS="4"
CFG_ATTENTION_QUANT="awq"
CFG_SHARED_EXPERT_QUANT="int8"
CFG_DENSE_MLP_QUANT="int8"
CFG_LM_HEAD_QUANT="int8"
PPLCONF
info "=== [PPL] $model (INT4/AWQ) ==="
session-send "$SESSION_WS" "[PPL] Starting: $model" 2>/dev/null || true
local ppl_start
ppl_start=$(date +%s)
if do_perplexity "$ppl_conf" --max-tokens 20000; then
local ppl_elapsed=$(( $(date +%s) - ppl_start ))
local ppl_mins=$((ppl_elapsed / 60))
local ppl_secs=$((ppl_elapsed % 60))
ppl_passed=$((ppl_passed + 1))
ok "[PPL] PASSED: $model (${ppl_mins}m ${ppl_secs}s)"
session-send "$SESSION_WS" "[PPL] PASSED: $model (${ppl_mins}m ${ppl_secs}s)" 2>/dev/null || true
else
local ppl_elapsed=$(( $(date +%s) - ppl_start ))
local ppl_mins=$((ppl_elapsed / 60))
local ppl_secs=$((ppl_elapsed % 60))
ppl_failed=$((ppl_failed + 1))
warn "[PPL] FAILED: $model (${ppl_mins}m ${ppl_secs}s)"
session-send "$SESSION_WS" "[PPL] FAILED: $model (${ppl_mins}m ${ppl_secs}s)" 2>/dev/null || true
fi
rm -f "$ppl_conf"
done
# ── Final summary ──────────────────────────────────────────────
local total_elapsed=$(( $(date +%s) - start_time ))
local total_mins=$((total_elapsed / 60))
local total_secs=$((total_elapsed % 60))
local final_msg="COMPLETE: $completed/$total models passed, perplexity $ppl_passed/$total passed, total ${total_mins}m ${total_secs}s.${target_suffix}"
ok "$final_msg"
session-send "$SESSION_WS" "$final_msg" 2>/dev/null || true
# Clean up state file on full success
if [[ -n "$state_file" ]]; then
rm -f "$state_file"
info "State file removed (all passed)."
fi
}
do_benchmark() {
[[ $# -lt 1 ]] && err "Usage: ./dev benchmark <config> [extra server args...]"
local conf
conf=$(resolve_config "$1")
shift
cleanup_gpu "$conf"
auto_rebuild
local run_dir
run_dir=$(create_run_dir "dev-benchmark")
local logfile
logfile="$run_dir/benchmark_stdout.log"
info "Running standard benchmark: $conf"
info "Run dir: $run_dir"
info "Log: $logfile"
verify_repo_imports
cd "$SCRIPT_DIR" && KRASIS_RUN_DIR="$run_dir" KRASIS_RUN_TYPE="dev-benchmark" run_repo_python -m krasis.server --config "$conf" --benchmark-only "$@" 2>&1 | tee "$logfile"
info "Benchmark log saved: $logfile"
}