-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathautodevops_cli.py
More file actions
1794 lines (1612 loc) · 67.4 KB
/
autodevops_cli.py
File metadata and controls
1794 lines (1612 loc) · 67.4 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 python3
"""Interactive TUI front-end for autodevops.py builds."""
from __future__ import annotations
import curses
import locale
import platform
import shutil
import subprocess
import sys
import textwrap
from dataclasses import dataclass
from pathlib import Path
from typing import Callable, List, Sequence, Set
import autodevops
import tui_utils
from constants import AUTODEVOPS_LAYOUT
from keybindings import KEYS
from tui_base import (
UIState,
append_log,
apply_saved_values,
draw_logs,
format_scroll_indicator,
layout_mode,
load_saved_state,
prepare_help_panel,
save_state,
)
SCRIPT_DIR = Path(__file__).resolve().parent
AUTO_SCRIPT = SCRIPT_DIR / "autodevops.py"
CONFIG_PATH = SCRIPT_DIR / ".autodevops_cli.json"
locale.setlocale(locale.LC_ALL, "")
STRINGS = {
"title": "llama.cpp AutodevOps Builder",
"instructions": "Arrows: navigate • Space: toggle/cycle • Enter: edit/apply • PgUp/PgDn: scroll • Tab: cycle panes • ?: toggle help • c: compact • q: quit",
"logs_heading": "Logs",
"help_heading": "Help",
"no_space_warning": "Not enough space to render menu. Enlarge the window.",
"suggest_install_cuda": "NVCC not detected. Install the CUDA toolkit or export CUDA_HOME to enable CUDA builds and fast math.",
}
@dataclass
class ChoiceValue:
label: str
value: str
enabled: bool = True
reason: str | None = None
@dataclass
class SystemInfo:
cpu_vendor: str
cpu_flags: Set[str]
arch: str
gpu_vendor: str
cuda_home: Path | None
has_mkl: bool
has_openblas: bool
has_blis: bool
@dataclass
class TUIConfig:
show_unavailable: bool = False
show_hardware_badges: bool = True
compact_list: bool = True
class OptionBase:
key: str
name: str
description: str
help_text: str
disabled: bool
reason: str | None
default_value: object
icon: str = "[OPT]"
def __init__(self, *, ui_config: TUIConfig | None = None) -> None:
self._ui_config = ui_config
def _is_compact(self) -> bool:
if self._ui_config is None:
return False
return bool(self._ui_config.compact_list)
def render(self, win: "curses._CursesWindow", y: int, width: int, selected: bool) -> int:
raise NotImplementedError
def handle_key(self, key: int) -> None:
pass
def height(self, width: int) -> int:
return 1
def get_help(self) -> str:
return self.help_text or self.description
def is_modified(self) -> bool:
return False
def get_summary(self, width: int) -> str:
help_text = self.get_help().strip().splitlines()
if not help_text:
return ""
summary = help_text[0].strip()
if len(summary) > width:
summary = summary[: max(0, width - 1)] + "…"
return summary
def get_value(self):
raise NotImplementedError
def set_value(self, value) -> None:
raise NotImplementedError
class ToggleOption(OptionBase):
def __init__(
self,
key: str,
name: str,
description: str,
value: bool = False,
*,
disabled: bool = False,
reason: str | None = None,
help_text: str = "",
on_change: Callable[[bool], None] | None = None,
ui_config: TUIConfig | None = None,
) -> None:
super().__init__(ui_config=ui_config)
self.key = key
self.name = name
self.description = description
self.help_text = help_text or description
self.value = value
self.disabled = disabled
self.reason = reason
self._on_change = on_change
self.default_value = value
def toggle(self) -> None:
if not self.disabled:
self.value = not self.value
if self._on_change is not None:
self._on_change(self.value)
def handle_key(self, key: int) -> None:
if key in KEYS.CONFIRM or key in (ord(" "), ord("t")):
self.toggle()
def render(self, win: "curses._CursesWindow", y: int, width: int, selected: bool) -> int:
attr = curses.A_REVERSE if selected else curses.A_NORMAL
if self.disabled:
attr |= curses.color_pair(2)
marker = "*" if self.is_modified() else " "
label = f"{marker}[TGL] {'[x]' if self.value else '[ ]'} {self.name}"
win.addnstr(y, 2, label, max(10, width - 4), attr)
if self._is_compact():
return 1
summary = self.get_summary(max(0, width - len(label) - 6))
if summary:
win.addnstr(y, min(width - 2, 2 + len(label) + 1), f" · {summary}", max(10, width - len(label) - 4), curses.A_DIM)
line_count = 1
desc_attr = curses.A_DIM
if self.disabled:
desc_attr |= curses.color_pair(2)
wrap_width = max(10, width - 6)
for line in textwrap.wrap(self.description, wrap_width):
win.addnstr(y + line_count, 6, line, max(10, width - 8), desc_attr)
line_count += 1
if self.disabled and self.reason:
reason = f"⚠ {self.reason}"
win.addnstr(y + line_count, 6, reason, max(10, width - 8), curses.color_pair(2) | curses.A_DIM)
line_count += 1
return line_count
def height(self, width: int) -> int:
if self._is_compact():
return 1
wrap_width = max(10, width - 6)
base = 1 + len(textwrap.wrap(self.description, wrap_width))
if self.disabled and self.reason:
base += 1
return base
def is_modified(self) -> bool:
return self.value != self.default_value
def get_value(self) -> bool:
return bool(self.value)
def set_value(self, value) -> None:
self.value = bool(value)
if self._on_change is not None:
self._on_change(self.value)
class ChoiceOption(OptionBase):
def __init__(
self,
key: str,
name: str,
description: str,
choices: Sequence[ChoiceValue],
*,
initial: str | None = None,
help_text: str = "",
show_unavailable_fn: Callable[[], bool] | None = None,
ui_config: TUIConfig | None = None,
) -> None:
super().__init__(ui_config=ui_config)
if not choices:
raise ValueError("choices cannot be empty")
self.key = key
self.name = name
self.description = description
self.help_text = help_text or description
self.choices = list(choices)
self.disabled = all(not c.enabled for c in self.choices)
self.reason = None
if self.disabled:
self.reason = "No enabled options"
self._show_unavailable_fn = show_unavailable_fn
self.index = 0
self.default_value = None
if initial is not None:
for idx, c in enumerate(self.choices):
if c.value == initial:
self.index = idx
break
if not self.choices[self.index].enabled:
self._select_next_enabled(1)
self.default_value = self.choices[self.index].value
def _select_next_enabled(self, delta: int) -> None:
if self.disabled:
return
count = len(self.choices)
for _ in range(count):
self.index = (self.index + delta) % count
if self.choices[self.index].enabled:
return
def handle_key(self, key: int) -> None:
if key in KEYS.NAV_LEFT:
self._select_next_enabled(-1)
elif key in KEYS.NAV_RIGHT:
self._select_next_enabled(1)
def render(self, win: "curses._CursesWindow", y: int, width: int, selected: bool) -> int:
attr = curses.A_REVERSE if selected else curses.A_NORMAL
current = self.choices[self.index]
if self.disabled:
attr |= curses.color_pair(2)
marker = "*" if self.is_modified() else " "
label = f"{marker}[SEL] {self.name}: {current.label}"
win.addnstr(y, 2, label, max(10, width - 4), attr)
if self._is_compact():
return 1
summary = self.get_summary(max(0, width - len(label) - 6))
if summary:
win.addnstr(y, min(width - 2, 2 + len(label) + 1), f" · {summary}", max(10, width - len(label) - 4), curses.A_DIM)
line_count = 1
desc_attr = curses.A_DIM
if self.disabled:
desc_attr |= curses.color_pair(2)
wrap_width = max(10, width - 6)
for line in textwrap.wrap(self.description, wrap_width):
win.addnstr(y + line_count, 6, line, max(10, width - 8), desc_attr)
line_count += 1
if not current.enabled and current.reason:
reason = f"⚠ {current.reason}"
win.addnstr(y + line_count, 6, reason, max(10, width - 8), curses.color_pair(2) | curses.A_DIM)
line_count += 1
show_unavailable = self._show_unavailable_fn() if self._show_unavailable_fn else False
if show_unavailable:
unavailable = [c for c in self.choices if not c.enabled]
if unavailable:
win.addnstr(y + line_count, 6, "Unavailable:", max(10, width - 8), curses.A_DIM)
line_count += 1
for choice in unavailable:
text = choice.label
if choice.reason:
text += f" — {choice.reason}"
list_width = max(10, width - 10)
wrapped = textwrap.wrap(text, list_width) or [""]
for idx, chunk in enumerate(wrapped):
prefix = "• " if idx == 0 else " "
win.addnstr(y + line_count, 8, prefix + chunk, max(10, list_width), curses.A_DIM)
line_count += 1
return line_count
def height(self, width: int) -> int:
if self._is_compact():
return 1
wrap_width = max(10, width - 6)
base = 1 + len(textwrap.wrap(self.description, wrap_width))
current = self.choices[self.index]
if not current.enabled and current.reason:
base += 1
show_unavailable = self._show_unavailable_fn() if self._show_unavailable_fn else False
if show_unavailable:
unavailable = [c for c in self.choices if not c.enabled]
if unavailable:
base += 1
for choice in unavailable:
text = choice.label
if choice.reason:
text += f" — {choice.reason}"
list_width = max(10, width - 10)
wrapped = textwrap.wrap(text, list_width) or [""]
base += len(wrapped)
return base
def is_modified(self) -> bool:
selected = self.choices[self.index].value
return selected != self.default_value
def get_value(self):
return self.choices[self.index].value
def set_value(self, value) -> None:
for idx, choice in enumerate(self.choices):
if choice.value == value:
self.index = idx
break
@property
def value(self) -> ChoiceValue:
return self.choices[self.index]
class InputOption(OptionBase):
def __init__(
self,
key: str,
name: str,
description: str,
value: str,
placeholder: str = "",
help_text: str = "",
ui_config: TUIConfig | None = None,
) -> None:
super().__init__(ui_config=ui_config)
self.key = key
self.name = name
self.description = description
self.help_text = help_text or description
self.value = value
self.placeholder = placeholder
self.disabled = False
self.reason = None
self.default_value = value
def edit(self, stdscr: "curses._CursesWindow") -> None:
result = tui_utils.edit_line_dialog(
stdscr,
title=f"Edit {self.name}",
initial=self.value,
allow_empty=True,
)
if result.accepted:
self.value = result.value
def handle_key(self, key: int, stdscr: "curses._CursesWindow" | None = None) -> None:
if key in KEYS.CONFIRM and stdscr is not None:
self.edit(stdscr)
def render(self, win: "curses._CursesWindow", y: int, width: int, selected: bool) -> int:
attr = curses.A_REVERSE if selected else curses.A_NORMAL
marker = "*" if self.is_modified() else " "
display = self.value or self.placeholder
label = f"{marker}[TXT] {self.name}: {display}"
win.addnstr(y, 2, label, max(10, width - 4), attr)
if self._is_compact():
return 1
summary = self.get_summary(max(0, width - len(label) - 6))
if summary:
win.addnstr(y, min(width - 2, 2 + len(label) + 1), f" · {summary}", max(10, width - len(label) - 4), curses.A_DIM)
line_count = 1
wrap_width = max(10, width - 6)
for line in textwrap.wrap(self.description, wrap_width):
win.addnstr(y + line_count, 6, line, max(10, width - 8), curses.A_DIM)
line_count += 1
return line_count
def height(self, width: int) -> int:
if self._is_compact():
return 1
wrap_width = max(10, width - 6)
return 1 + len(textwrap.wrap(self.description, wrap_width))
def is_modified(self) -> bool:
return self.value != self.default_value
def get_value(self) -> str:
return self.value
def set_value(self, value) -> None:
if value is None:
return
self.value = str(value)
class InfoBadgeOption(OptionBase):
def __init__(
self,
key: str,
name: str,
description: str,
*,
help_text: str = "",
icon: str = "ℹ",
visible_fn: Callable[[], bool] | None = None,
ui_config: TUIConfig | None = None,
) -> None:
super().__init__(ui_config=ui_config)
self.key = key
self.name = name
self.description = description
self.help_text = help_text or description
self.icon = icon
self._visible_fn = visible_fn
self.disabled = False
self.reason = None
def _visible(self) -> bool:
if self._visible_fn is None:
return True
return self._visible_fn()
def render(self, win: "curses._CursesWindow", y: int, width: int, selected: bool) -> int:
if not self._visible():
return 0
attr = curses.A_REVERSE if selected else curses.A_DIM
label = f"{self.icon} {self.name}"
win.addnstr(y, 2, label, max(10, width - 4), attr)
if self._is_compact():
return 1
line_count = 1
wrap_width = max(10, width - 6)
for line in textwrap.wrap(self.description, wrap_width):
win.addnstr(y + line_count, 6, line, max(10, width - 8), curses.A_DIM)
line_count += 1
return line_count
def handle_key(self, key: int) -> None:
return
def height(self, width: int) -> int:
if not self._visible():
return 0
if self._is_compact():
return 1
wrap_width = max(10, width - 6)
return 1 + len(textwrap.wrap(self.description, wrap_width))
def get_value(self):
return None
def set_value(self, value) -> None:
return
def detect_cpu_vendor() -> str:
cpuinfo = Path("/proc/cpuinfo")
if cpuinfo.exists():
for line in cpuinfo.read_text().splitlines():
if line.lower().startswith("vendor_id"):
vendor = line.split(":", 1)[1].strip().lower()
if "intel" in vendor:
return "intel"
if "amd" in vendor or "hygon" in vendor:
return "amd"
return "unknown"
def detect_gpu_vendor() -> str:
if shutil.which("nvidia-smi"):
return "nvidia"
try:
out = subprocess.check_output(["lspci"], text=True, stderr=subprocess.DEVNULL)
except Exception:
out = ""
out_lower = out.lower()
if "nvidia" in out_lower:
return "nvidia"
if "amd" in out_lower or "advanced micro devices" in out_lower:
return "amd"
if "intel" in out_lower and "vga" in out_lower:
return "intel"
return "unknown"
def detect_cpu_flags() -> Set[str]:
flags: Set[str] = set()
cpuinfo = Path("/proc/cpuinfo")
if cpuinfo.exists():
for line in cpuinfo.read_text().splitlines():
low = line.lower()
if low.startswith("flags") or low.startswith("features"):
_, _, raw_flags = line.partition(":")
flags.update(flag.strip().lower() for flag in raw_flags.split())
return flags
def blis_present() -> bool:
candidates = [
"/usr/lib/x86_64-linux-gnu/libblis.so",
"/usr/lib/x86_64-linux-gnu/libblis.so.*",
"/opt/amd/aocl/lib/libblis.so",
"/opt/amd/aocl/lib/libblis.so.*",
]
try:
return autodevops._lib_present(candidates) # type: ignore[attr-defined]
except AttributeError:
return False
def collect_system_info() -> SystemInfo:
cpu_vendor = detect_cpu_vendor()
gpu_vendor = detect_gpu_vendor()
flags = detect_cpu_flags()
arch = platform.machine().lower()
cuda_home = autodevops.pick_cuda_home()
has_mkl = autodevops.mkl_present()
has_openblas = autodevops.openblas_present()
has_blis = blis_present()
return SystemInfo(
cpu_vendor=cpu_vendor,
cpu_flags=flags,
arch=arch,
gpu_vendor=gpu_vendor,
cuda_home=cuda_home,
has_mkl=has_mkl,
has_openblas=has_openblas,
has_blis=has_blis,
)
def _attach_detection_metadata(config: dict, info: SystemInfo) -> dict:
enriched = dict(config)
enriched["detected_gpu_vendor"] = info.gpu_vendor
enriched["detected_cuda_home"] = str(info.cuda_home) if info.cuda_home else None
return enriched
def build_options(system_info: SystemInfo | None = None, ui_config: TUIConfig | None = None) -> List[OptionBase]:
"""Build the interactive option list.
Parameters
----------
system_info:
Optional :class:`SystemInfo` instance to seed the wizard. Providing a
pre-computed value makes it easy to unit test the menu logic without
touching real hardware probes.
"""
ui_config = ui_config or TUIConfig()
info = system_info or collect_system_info()
cpu_vendor = info.cpu_vendor
gpu_vendor = info.gpu_vendor
has_cuda = info.cuda_home is not None
fast_math_disabled = not has_cuda
fast_math_reason = None
if fast_math_disabled:
if gpu_vendor == "nvidia":
fast_math_reason = "NVCC (CUDA Toolkit) not found — set CUDA_HOME or install cuda-toolkit"
else:
fast_math_reason = "NVCC not found on this system"
blas_choices = [
ChoiceValue("Auto", "auto"),
ChoiceValue("Intel oneAPI MKL", "mkl", info.has_mkl, "Intel MKL libraries not detected"),
ChoiceValue("OpenBLAS", "openblas", info.has_openblas, "OpenBLAS libraries not detected"),
ChoiceValue("AMD BLIS", "blis", info.has_blis, "AMD BLIS libraries not detected"),
ChoiceValue("Disabled", "off"),
]
backend_choices = [
ChoiceValue(
"CUDA (NVIDIA)",
"cuda",
has_cuda,
"CUDA Toolkit not found (set CUDA_HOME or install cuda-toolkit)" if not has_cuda else None,
),
ChoiceValue("ROCm (AMD)", "rocm", gpu_vendor == "amd", "ROCm toolchain not detected"),
ChoiceValue("oneAPI / SYCL (Intel)", "oneapi", gpu_vendor == "intel", "Intel oneAPI compilers not detected"),
ChoiceValue("Vulkan (universal)", "vulkan", True),
ChoiceValue("CPU only", "cpu", True),
]
has_avx2 = "avx2" in info.cpu_flags
has_avx512 = any(flag.startswith("avx512") for flag in info.cpu_flags)
has_avx_vnni = any(flag in info.cpu_flags for flag in ("avxvnni", "avx_vnni", "avx512_vnni"))
is_arm = info.arch in {"aarch64", "arm64"}
cpu_choices = [
ChoiceValue("Auto (detect)", "auto"),
ChoiceValue(
"Intel AVX2", "intel_avx2", enabled=cpu_vendor == "intel" and has_avx2,
reason="Requires an Intel CPU with AVX2"
),
ChoiceValue(
"Intel AVX-512 + MKL", "intel_avx512",
enabled=cpu_vendor == "intel" and has_avx512,
reason="CPU does not report AVX-512 support"
),
ChoiceValue(
"AMD Zen 3/4 (OpenBLAS)", "amd_zen", enabled=cpu_vendor == "amd" and has_avx2,
reason="Requires an AMD CPU with AVX2"
),
ChoiceValue(
"AMD Zen 4 + VNNI", "amd_zen4",
enabled=cpu_vendor == "amd" and has_avx_vnni,
reason="AVX-VNNI extensions not detected"
),
ChoiceValue(
"ARM64 / Apple Silicon", "arm64", enabled=is_arm,
reason="Machine is not reporting ARM64"
),
ChoiceValue("Generic portable", "generic"),
]
runtime_choices = [
ChoiceValue("Balanced", "balanced"),
ChoiceValue("High-memory throughput", "high_mem"),
ChoiceValue("Memory constrained", "low_mem"),
ChoiceValue("Multi-GPU", "multi_gpu"),
]
quant_choices = [
ChoiceValue("Auto", "auto"),
ChoiceValue("FP16 focus", "fp16"),
ChoiceValue("INT8 speed", "int8"),
ChoiceValue("Q4_K_M compact", "q4_k_m"),
]
options: List[OptionBase] = [
InputOption(
"ref",
"Target ref",
"Git tag, branch, or commit to build. Use 'latest' to fetch the newest release.",
value="latest",
placeholder="latest",
help_text=(
"Set which llama.cpp revision to build. "
"The wizard will fetch releases automatically when 'latest' is used."
),
ui_config=ui_config,
),
ToggleOption(
"now",
"Build immediately",
"Run the build as soon as you exit this wizard.",
value=True,
help_text=(
"If enabled, autodevops.py is launched as soon as you press Start. "
"Disable it to just print the recommended commands without running them."
),
ui_config=ui_config,
),
ToggleOption(
"_show_unavailable",
"Show unavailable choices",
"Display disabled presets with explanations below each selector.",
value=ui_config.show_unavailable,
help_text=(
"Enabling this reveals options that are currently disabled along with the"
" reason they are unavailable on this system."
),
on_change=lambda value: setattr(ui_config, "show_unavailable", value),
ui_config=ui_config,
),
ToggleOption(
"_show_hardware_badges",
"Show hardware detection badges",
"Toggle informational badges that summarise detected CPUs and GPUs.",
value=ui_config.show_hardware_badges,
help_text=(
"Hardware badges highlight detected vendors and suggested build tips."
" Disable this if you prefer a minimal menu."
),
on_change=lambda value: setattr(ui_config, "show_hardware_badges", value),
ui_config=ui_config,
),
ChoiceOption(
"backend",
"GPU backend",
"Available GPU accelerators based on detected hardware.",
backend_choices,
show_unavailable_fn=lambda: ui_config.show_unavailable,
help_text=(
"Choose which accelerator backend to prepare for.\n"
" • CUDA: native NVIDIA support with MMQ/cuBLAS kernels.\n"
" • ROCm: AMD RDNA/CDNA GPUs using hipcc (see advanced cmake example above).\n"
" • oneAPI/SYCL: Intel GPUs via icx/icpx compilers.\n"
" • Vulkan: universal backend ~7% slower but works across vendors.\n"
" • CPU only: build without GPU offload."
),
ui_config=ui_config,
),
ChoiceOption(
"cpu_profile",
"CPU optimization profile",
"Selects tuned CMake flags derived from the comprehensive compilation guide.",
cpu_choices,
show_unavailable_fn=lambda: ui_config.show_unavailable,
help_text=(
"Curated CPU build presets:\n"
" • Intel AVX2: -DGGML_AVX=ON -DGGML_AVX2=ON with -O3 -march=native.\n"
" • Intel AVX-512 + MKL: adds -DGGML_AVX512=ON and Intel oneAPI MKL toolchain.\n"
" • AMD Zen 3/4: enables AVX2/VNNI paths with OpenBLAS or BLIS.\n"
" • ARM64: lean build relying on Apple Metal/Accelerate or -mcpu flags.\n"
"Auto mode picks the best option based on detected vendor/features."
),
ui_config=ui_config,
),
ChoiceOption(
"blas",
"CPU BLAS backend",
"Select BLAS acceleration for CPU fallbacks.",
blas_choices,
initial="auto",
show_unavailable_fn=lambda: ui_config.show_unavailable,
help_text=(
"Compare BLAS libraries: MKL excels on Intel, OpenBLAS is versatile, and AMD BLIS"
" leads on Ryzen. Built-in GGML kernels can win for token generation."
),
ui_config=ui_config,
),
ChoiceOption(
"force_mmq",
"Force MMQ kernels",
"Controls GGML_CUDA_FORCE_MMQ. 'Auto' enables it on newer NVIDIA GPUs.",
[
ChoiceValue("Auto", "auto"),
ChoiceValue("On", "on"),
ChoiceValue("Off", "off"),
],
show_unavailable_fn=lambda: ui_config.show_unavailable,
help_text=(
"Force the mixed-memory (MMQ) CUDA kernels. Auto lets llama.cpp choose between"
" cuBLAS and MMQ depending on tensor-core support. Disable if older GPUs misbehave."
),
ui_config=ui_config,
),
ToggleOption(
"fast_math",
"Enable fast math",
"Adds --use_fast_math to NVCC for potential speedups at the cost of precision.",
value=False,
disabled=fast_math_disabled,
reason=fast_math_reason,
help_text=(
"Fast math maps transcendental ops to lower-precision CUDA intrinsics."
" Use it on inference-only systems when you can tolerate minor accuracy drift."
),
ui_config=ui_config,
),
ToggleOption(
"distributed",
"Enable distributed RPC backend",
"Compile llama.cpp with GGML_RPC so rpc-server and multi-host inference are available.",
value=False,
help_text=(
"Turns on the GGML RPC build path. Requires NCCL/MPI and is currently considered"
" proof-of-concept; run only on trusted networks."
),
ui_config=ui_config,
),
ToggleOption(
"unified_memory",
"Enable CUDA unified memory",
"Sets GGML_CUDA_ENABLE_UNIFIED_MEMORY=1 at runtime for oversized models.",
value=False,
help_text=(
"Unified memory lets CUDA spill activations into system RAM, enabling models"
" larger than VRAM at the cost of PCIe traffic. Combine with partial CPU offload."
),
ui_config=ui_config,
),
ToggleOption(
"flash_attention",
"Prefer Flash Attention",
"Reminds you to run llama-cli with -fa for faster prompt processing.",
value=True,
help_text=(
"Flash Attention reduces memory usage and improves prompt throughput."
" The runtime flag is '-fa' in llama-cli."
),
ui_config=ui_config,
),
ChoiceOption(
"runtime_profile",
"Runtime tuning profile",
"Suggests llama-cli runtime arguments tailored to your system budget.",
runtime_choices,
show_unavailable_fn=lambda: ui_config.show_unavailable,
help_text=(
"Quick-start runtime templates:\n"
" • Balanced: -t (nproc) -ngl 35 -c 8192 -b 1024 --cache-reuse 256.\n"
" • High-memory: -t (nproc) -ngl 35 -c 16384 -b 2048 --mlock --no-mmap.\n"
" • Memory constrained: -t 8 -ngl 20 -c 4096 -b 512 --tensor-split 0.6,0.4.\n"
" • Multi-GPU: --tensor-split auto --main-gpu 0 -ngl 80 (NVLink) or manual splits."
),
ui_config=ui_config,
),
ChoiceOption(
"quantization",
"Quantization focus",
"Guides which GGUF quantization families to prioritise when downloading models.",
quant_choices,
show_unavailable_fn=lambda: ui_config.show_unavailable,
help_text=(
"FP16 maximises quality on capable GPUs. INT8 (Q8_0) balances speed and size."
" Q4_K_M keeps small VRAM footprints with acceptable quality for chatbots."
),
ui_config=ui_config,
),
]
# Informational badges
if cpu_vendor == "intel":
options.append(
InfoBadgeOption(
"_info_cpu",
"Intel CPU detected",
"Optimised Intel builds with MKL are available when libraries are installed.",
help_text=(
"Detected Intel CPU. Consider the advanced MKL recipe:\n"
" source /opt/intel/oneapi/setvars.sh\n"
" cmake -B build -DGGML_BLAS=ON -DGGML_BLAS_VENDOR=Intel10_64lp\n"
" -DCMAKE_C_COMPILER=icx -DCMAKE_CXX_COMPILER=icpx\n"
" -DGGML_AVX=ON -DGGML_AVX2=ON -DGGML_AVX512=ON\n"
" -DCMAKE_C_FLAGS=\"-O3 -ipo -static -fp-model=fast -march=native\""
),
icon="🧠",
visible_fn=lambda: ui_config.show_hardware_badges,
ui_config=ui_config,
)
)
elif cpu_vendor == "amd":
options.append(
InfoBadgeOption(
"_info_cpu",
"AMD CPU detected",
"Install OpenBLAS/BLIS for the best CPU throughput.",
help_text=(
"Detected AMD CPU. Recommended build:\n"
" cmake -B build -DGGML_AVX=ON -DGGML_AVX2=ON -DGGML_AVX_VNNI=ON\n"
" -DGGML_BLAS=ON -DGGML_BLAS_VENDOR=BLIS\n"
" -DCMAKE_C_FLAGS=\"-O3 -march=native -mavx2 -mcpu=native\""
),
icon="🧠",
visible_fn=lambda: ui_config.show_hardware_badges,
ui_config=ui_config,
)
)
elif is_arm:
options.append(
InfoBadgeOption(
"_info_cpu",
"ARM64 CPU detected",
"Apple/ARM builds can enable Metal or Accelerate backends automatically.",
help_text=(
"On Apple Silicon run: cmake -B build -DGGML_METAL=ON and make llama-cli."
),
icon="🧠",
visible_fn=lambda: ui_config.show_hardware_badges,
ui_config=ui_config,
)
)
if gpu_vendor == "nvidia":
options.append(
InfoBadgeOption(
"_info_gpu",
"NVIDIA GPU detected",
"CUDA builds are available on this system.",
help_text=(
"Recommended CUDA command:\n"
" cmake -B build -DGGML_CUDA=ON -DGGML_CUDA_F16=ON\n"
" -DGGML_CUDA_PEER_MAX_BATCH_SIZE=128 -DCMAKE_CUDA_ARCHITECTURES=native"
),
icon="🎮",
visible_fn=lambda: ui_config.show_hardware_badges,
ui_config=ui_config,
)
)
elif gpu_vendor == "amd":
options.append(
InfoBadgeOption(
"_info_gpu",
"AMD GPU detected",
"ROCm builds are supported manually via hipcc.",
help_text=(
"Export CC=/opt/rocm/llvm/bin/clang and run cmake -DGGML_HIP=ON -DAMDGPU_TARGETS=native."
),
icon="🎮",
visible_fn=lambda: ui_config.show_hardware_badges,
ui_config=ui_config,
)
)
elif gpu_vendor == "intel":
options.append(
InfoBadgeOption(
"_info_gpu",
"Intel GPU detected",
"Use oneAPI SYCL builds with icx/icpx compilers.",
help_text=(
"source /opt/intel/oneapi/setvars.sh and cmake -DGGML_SYCL=ON -DGGML_SYCL_F16=ON."
),
icon="🎮",
visible_fn=lambda: ui_config.show_hardware_badges,
ui_config=ui_config,
)
)
return options
def compile_config(options: Sequence[OptionBase]) -> dict:
config: dict = {}
for opt in options:
if opt.key.startswith("_"):
continue
if isinstance(opt, InputOption):
config[opt.key] = opt.value
elif isinstance(opt, ToggleOption):
config[opt.key] = opt.value
elif isinstance(opt, ChoiceOption):
config[opt.key] = opt.value.value
return config
def cpu_profile_instructions(profile: str) -> str:
mapping = {
"intel_avx2": "cmake -B build -DGGML_AVX=ON -DGGML_AVX2=ON -DCMAKE_BUILD_TYPE=Release \\\n+ -DCMAKE_C_FLAGS=\"-O3 -march=native -mavx2\" -DCMAKE_CXX_FLAGS=\"-O3 -march=native -mavx2\"",
"intel_avx512": "source /opt/intel/oneapi/setvars.sh\ncmake -B build -DGGML_BLAS=ON -DGGML_BLAS_VENDOR=Intel10_64lp \\\n+ -DCMAKE_C_COMPILER=icx -DCMAKE_CXX_COMPILER=icpx -DGGML_AVX=ON -DGGML_AVX2=ON -DGGML_AVX512=ON \\\n+ -DCMAKE_C_FLAGS=\"-O3 -ipo -static -fp-model=fast -march=native\"",
"amd_zen": "cmake -B build -DGGML_AVX=ON -DGGML_AVX2=ON -DGGML_AVX_VNNI=ON -DCMAKE_BUILD_TYPE=Release \\\n+ -DCMAKE_C_FLAGS=\"-O3 -march=native -mavx2 -mcpu=native\" -DCMAKE_CXX_FLAGS=\"-O3 -march=native -mavx2 -mcpu=native\"",
"amd_zen4": "cmake -B build -DGGML_AVX=ON -DGGML_AVX2=ON -DGGML_AVX_VNNI=ON -DGGML_BLAS=ON -DGGML_BLAS_VENDOR=BLIS",
"arm64": "cmake -B build -DCMAKE_C_FLAGS=\"-O3 -mcpu=native -march=native\" -DCMAKE_CXX_FLAGS=\"-O3 -mcpu=native -march=native\"",
"generic": "cmake -B build -DCMAKE_BUILD_TYPE=Release -DGGML_NATIVE=OFF",
}
return mapping.get(profile, "")
def backend_instructions(backend: str) -> str:
mapping = {
"cuda": "cmake -B build -DGGML_CUDA=ON -DGGML_CUDA_F16=ON -DGGML_CUDA_PEER_MAX_BATCH_SIZE=128 \\\n+ -DGGML_CUDA_FA_ALL_QUANTS=ON -DCMAKE_CUDA_ARCHITECTURES=native",
"rocm": "export CC=/opt/rocm/llvm/bin/clang\nexport CXX=/opt/rocm/llvm/bin/clang++\ncmake -B build -DGGML_HIP=ON -DAMDGPU_TARGETS=native -DGGML_HIP_ROCWMMA_FATTN=ON",
"oneapi": "source /opt/intel/oneapi/setvars.sh\ncmake -B build -DGGML_SYCL=ON -DGGML_SYCL_F16=ON -DGGML_SYCL_TARGET=INTEL -DCMAKE_C_COMPILER=icx -DCMAKE_CXX_COMPILER=icpx",
"vulkan": "cmake -B build -DGGML_VULKAN=ON -DGGML_AVX=ON -DGGML_AVX2=ON",
"cpu": "cmake -B build -DGGML_CUDA=OFF -DGGML_HIP=OFF -DGGML_VULKAN=OFF",
}
return mapping.get(backend, "")
def blas_instructions(vendor: str) -> str:
if vendor == "mkl":
return autodevops.blas_hint("mkl")
if vendor == "openblas":
return autodevops.blas_hint("openblas")
if vendor == "blis":
return (
"Install AMD BLIS (part of AOCL) and export BLIS_NUM_THREADS=auto for optimal scaling."
)
return ""
def runtime_profile_instructions(profile: str) -> str:
mapping = {
"balanced": "./llama-cli -t $(nproc) -ngl 35 -c 8192 -b 1024 --cache-reuse 256",
"high_mem": "./llama-cli -t $(nproc) -ngl 35 -c 16384 -b 2048 --mlock --no-mmap --cache-reuse 256",
"low_mem": "./llama-cli -t 8 -ngl 20 -c 4096 -b 512 --tensor-split 0.6,0.4",
"multi_gpu": "./llama-cli --tensor-split auto --main-gpu 0 -ngl 80",
}
return mapping.get(profile, "")
def quantization_notes(flavour: str) -> str:
mapping = {
"fp16": "Use GGUF models ending with -F16 for highest fidelity on modern GPUs.",
"int8": "Prioritise GGUF Q8_0 for the best balance of speed and quality when VRAM allows.",
"q4_k_m": "Q4_K_M GGUF saves VRAM (~4 bits) yet keeps good chat accuracy; ideal for 8-12GB GPUs.",
}
return mapping.get(flavour, "")
def _draw_wide_layout(
stdscr: "curses._CursesWindow",