-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloadmodel_dist_cli.py
More file actions
1901 lines (1711 loc) · 67.6 KB
/
loadmodel_dist_cli.py
File metadata and controls
1901 lines (1711 loc) · 67.6 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 CLI for launching llama.cpp distributed (RPC) inference."""
from __future__ import annotations
import curses
import ipaddress
import os
import shlex
import subprocess
import sys
import textwrap
import threading
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Iterable, List, Optional, Tuple
import socket
from concurrent.futures import ThreadPoolExecutor
import tui_utils
import memory_utils
from constants import LOADMODEL_DIST_LAYOUT, UI
from keybindings import KEYS
from process_utils import register_process, unregister_process
from state_utils import StrictStateMixin
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,
)
from validators import split_extra_flags as validate_split_extra_flags
from validators import validate_int, validate_path, validate_port
SCRIPT_DIR = Path(__file__).resolve().parent
BIN_DIR = SCRIPT_DIR / "bin"
LLAMA_CLI = BIN_DIR / "llama-cli"
RPC_SERVER = BIN_DIR / "rpc-server"
MODELS_DIR = SCRIPT_DIR / "models"
DEFAULT_RPC_PORT = "5515"
CONFIG_PATH = SCRIPT_DIR / ".loadmodel_dist_cli.json"
STRINGS = {
"title": "llama.cpp Distributed Launcher",
"instructions": "Arrows: navigate • Enter: edit/activate • PgUp/PgDn: scroll • Tab: cycle panes • ?: toggle help • q: quit",
"logs_heading": "Logs",
"help_heading": "Help",
"no_space_warning": "Terminal too small for the launcher. Please enlarge.",
"scan_start": "Scanning local subnets for rpc-server instances…",
"scan_complete": "Network scan complete.",
"no_options": "No options available.",
}
@dataclass
class LoadModelDistState(StrictStateMixin):
models_dir: str = str(MODELS_DIR)
local_models: list[str] | None = None
selected_local_model: str = ""
model_path: str = ""
rpc_hosts: str = ""
ctx_size: str = ""
n_gpu_layers: str = "999"
batch_size: str = ""
tensor_cache: str = ""
prompt_file: str = ""
prompt_text: str = ""
extra_flags: str = ""
local_worker: bool = False
worker_host: str = "0.0.0.0"
worker_port: str = DEFAULT_RPC_PORT
worker_cache: str = ""
worker_devices: str = ""
worker_process: subprocess.Popen | None = None
discovered_hosts: list[str] | None = None
status: str = ""
def __post_init__(self) -> None:
if self.discovered_hosts is None:
self.discovered_hosts = []
def _option_detail_lines(opt: "OptionBase", state: dict) -> List[tuple[str, int]]:
lines: List[tuple[str, int]] = []
description = getattr(opt, "description", "")
if description:
lines.append((description, curses.A_NORMAL))
if isinstance(opt, ChoiceOption):
current = opt.current(state)
lines.append(("", 0))
lines.append((f"Current: {current.label}", curses.A_DIM))
lines.append(("Left/Right: change selection", curses.A_DIM))
if not current.enabled and current.reason:
lines.append((f"Note: {current.reason}", curses.A_DIM))
elif isinstance(opt, InputOption):
value = str(state.get(opt.key, "")).strip()
lines.append(("", 0))
lines.append((f"Current: {value or '(blank)'}", curses.A_DIM))
if opt.key == "worker_devices":
gpus_all = memory_utils.detect_gpus()
if not gpus_all:
lines.append(("No CUDA GPUs detected.", curses.A_DIM))
else:
indices, err = memory_utils.parse_device_list(value, gpus_all)
if err:
lines.append((f"⚠ {err}", curses.A_DIM))
elif indices is None:
lines.append(("Selected: all GPUs", curses.A_DIM))
elif not indices:
lines.append(("Selected: CPU-only", curses.A_DIM))
else:
joined = ", ".join(f"GPU{idx}" for idx in indices)
lines.append((f"Selected: {joined}", curses.A_DIM))
lines.append(("Detected GPUs:", curses.A_DIM))
for gpu in gpus_all:
total = memory_utils.format_bytes(gpu.total)
free = memory_utils.format_bytes(gpu.free)
if gpu.free is None:
lines.append((f"GPU{gpu.index}: {gpu.name} ({total} total)", curses.A_DIM))
else:
lines.append((f"GPU{gpu.index}: {gpu.name} ({free} free / {total} total)", curses.A_DIM))
lines.append(("Enter: edit (Enter saves, Esc cancels)", curses.A_DIM))
elif isinstance(opt, ToggleOption):
enabled = bool(state.get(opt.key))
lines.append(("", 0))
lines.append((f"State: {'enabled' if enabled else 'disabled'}", curses.A_DIM))
lines.append(("Space/Enter: toggle", curses.A_DIM))
elif isinstance(opt, ActionOption):
lines.append(("", 0))
lines.append(("Enter: run this action", curses.A_DIM))
if not lines:
lines.append(("No details available.", curses.A_DIM))
return lines
@dataclass
class ChoiceItem:
value: str
label: str
enabled: bool = True
reason: str | None = None
def _gpu_label(gpu: memory_utils.GPUInfo) -> str:
total = memory_utils.format_bytes(gpu.total)
free = memory_utils.format_bytes(gpu.free)
if gpu.free is None:
return f"GPU{gpu.index} {gpu.name} ({total} total)"
return f"GPU{gpu.index} {gpu.name} ({free} free / {total} total)"
def format_gpu_selection(value: str | None, gpus: List[memory_utils.GPUInfo]) -> str:
if not gpus:
return "cpu-only"
indices, err = memory_utils.parse_device_list(value, gpus)
if err:
return "invalid"
if indices is None:
return "all"
if not indices:
return "cpu-only"
return ",".join(str(idx) for idx in indices)
class OptionBase:
def __init__(
self,
key: str,
name: str,
description: str,
*,
visible: Callable[[dict], bool] | None = None,
) -> None:
self.key = key
self.name = name
self.description = description
self._visible = visible
self.icon = "[OPT]"
self.default_value = None
def is_visible(self, state: dict) -> bool:
if self._visible is None:
return True
try:
return bool(self._visible(state))
except Exception:
return True
def render(
self,
win: "curses._CursesWindow",
y: int,
width: int,
selected: bool,
state: dict,
) -> int:
raise NotImplementedError
def handle_key(
self,
key: int,
state: dict,
stdscr: "curses._CursesWindow",
) -> Tuple[bool, Optional[str]]:
return False, None
def height(self, width: int, state: dict) -> int:
raise NotImplementedError
def get_value(self, state: dict):
return state.get(self.key)
def set_value(self, state: dict, value) -> None:
state[self.key] = value
def is_modified(self, state: dict) -> bool:
return state.get(self.key) != self.default_value
def get_summary(self, width: int) -> str:
text = (self.description or "").strip()
if not text:
return ""
summary = text.splitlines()[0].strip()
if len(summary) > width:
summary = summary[: max(0, width - 1)] + "…"
return summary
class InputOption(OptionBase):
def __init__(
self,
key: str,
name: str,
description: str,
*,
placeholder: str = "",
on_change: Callable[[dict, str], None] | None = None,
visible: Callable[[dict], bool] | None = None,
) -> None:
super().__init__(key, name, description, visible=visible)
self.placeholder = placeholder
self._on_change = on_change
self.icon = "[TXT]"
self.default_value = None
def _edit(self, stdscr: "curses._CursesWindow", state: dict) -> None:
current = str(state.get(self.key, "")).strip()
result = tui_utils.edit_line_dialog(
stdscr,
title=f"Edit {self.name}",
initial=current,
allow_empty=True,
)
if not result.accepted:
return
if result.value != current:
state[self.key] = result.value
if self._on_change is not None:
self._on_change(state, result.value)
def handle_key(
self,
key: int,
state: dict,
stdscr: "curses._CursesWindow",
) -> Tuple[bool, Optional[str]]:
if key in KEYS.CONFIRM:
self._edit(stdscr, state)
return False, None
def render(
self,
win: "curses._CursesWindow",
y: int,
width: int,
selected: bool,
state: dict,
) -> int:
attr = curses.A_REVERSE if selected else curses.A_NORMAL
if self.default_value is None:
self.default_value = str(state.get(self.key, "") or "")
state.setdefault(self.key, self.default_value)
value = str(state.get(self.key, "")).strip()
display = value or self.placeholder
marker = "*" if self.is_modified(state) else " "
label = f"{marker}{self.icon} {self.name}: {display}"
win.addnstr(y, 2, label, max(10, width - 4), attr)
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, state: dict) -> int:
wrap_width = max(10, width - 6)
return 1 + len(textwrap.wrap(self.description, wrap_width))
def get_value(self, state: dict):
return state.get(self.key, "")
def set_value(self, state: dict, value) -> None:
state[self.key] = "" if value is None else str(value)
def is_modified(self, state: dict) -> bool:
baseline = "" if self.default_value is None else str(self.default_value)
return str(state.get(self.key, "")) != baseline
class DeviceSelectOption(InputOption):
def __init__(
self,
key: str,
name: str,
description: str,
*,
placeholder: str = "all GPUs",
on_change: Callable[[dict, str], None] | None = None,
visible: Callable[[dict], bool] | None = None,
) -> None:
super().__init__(
key,
name,
description,
placeholder=placeholder,
on_change=on_change,
visible=visible,
)
self.icon = "[GPU]"
def _edit(self, stdscr: "curses._CursesWindow", state: dict) -> None:
gpus = memory_utils.detect_gpus()
if not gpus:
state["status"] = "No CUDA GPUs detected."
return
items = [_gpu_label(gpu) for gpu in gpus]
current = str(state.get(self.key, "")).strip()
indices, err = memory_utils.parse_device_list(current, gpus)
if err:
state["status"] = err
index_map = {gpu.index: idx for idx, gpu in enumerate(gpus)}
if indices is None:
selected = list(range(len(gpus)))
else:
selected = [index_map[idx] for idx in indices if idx in index_map]
result = tui_utils.multi_select_dialog(
stdscr,
title=f"Select {self.name}",
items=items,
selected=selected,
)
if not result.accepted:
return
picked = [gpus[idx].index for idx in result.indices if 0 <= idx < len(gpus)]
if not picked:
value = "none"
elif len(picked) == len(gpus):
value = "all"
else:
value = ",".join(str(idx) for idx in picked)
if value != current:
state[self.key] = value
if self._on_change is not None:
self._on_change(state, value)
def render(
self,
win: "curses._CursesWindow",
y: int,
width: int,
selected: bool,
state: dict,
) -> int:
attr = curses.A_REVERSE if selected else curses.A_NORMAL
gpus_all = memory_utils.detect_gpus()
display = format_gpu_selection(state.get(self.key, ""), gpus_all) if gpus_all else "cpu-only"
marker = "*" if self.is_modified(state) else " "
label = f"{marker}{self.icon} {self.name}: {display}"
win.addnstr(y, 2, label, max(10, width - 4), attr)
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
class ToggleOption(OptionBase):
def __init__(
self,
key: str,
name: str,
description: str,
*,
visible: Callable[[dict], bool] | None = None,
) -> None:
super().__init__(key, name, description, visible=visible)
self.icon = "[TGL]"
self.default_value = None
def render(
self,
win: "curses._CursesWindow",
y: int,
width: int,
selected: bool,
state: dict,
) -> int:
attr = curses.A_REVERSE if selected else curses.A_NORMAL
if self.default_value is None:
self.default_value = bool(state.get(self.key, False))
state.setdefault(self.key, self.default_value)
mark = "✔" if state.get(self.key) else "✖"
marker = "*" if self.is_modified(state) else " "
label = f"{marker}{self.icon} [{mark}] {self.name}"
win.addnstr(y, 2, label, max(10, width - 4), attr)
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, state: dict) -> int:
wrap_width = max(10, width - 6)
return 1 + len(textwrap.wrap(self.description, wrap_width))
def handle_key(
self,
key: int,
state: dict,
stdscr: "curses._CursesWindow",
) -> Tuple[bool, Optional[str]]:
if key in KEYS.CONFIRM or key in (ord(" "), ord("t")):
state[self.key] = not bool(state.get(self.key))
return False, None
def get_value(self, state: dict):
return bool(state.get(self.key))
def set_value(self, state: dict, value) -> None:
state[self.key] = bool(value)
def is_modified(self, state: dict) -> bool:
baseline = bool(self.default_value) if self.default_value is not None else False
return bool(state.get(self.key)) != baseline
class ChoiceOption(OptionBase):
def __init__(
self,
key: str,
name: str,
description: str,
*,
state: dict,
choices: Iterable[ChoiceItem] | None = None,
choices_fn: Callable[[dict], Iterable[ChoiceItem]] | None = None,
on_change: Callable[[dict, ChoiceItem], None] | None = None,
visible: Callable[[dict], bool] | None = None,
) -> None:
super().__init__(key, name, description, visible=visible)
if choices is None and choices_fn is None:
raise ValueError("choices or choices_fn required")
self._static_choices = list(choices or [])
self._choices_fn = choices_fn
self._on_change = on_change
self._choices: List[ChoiceItem] = []
self._index = 0
self.icon = "[SEL]"
self.default_value = None
def _compute_choices(self, state: dict) -> None:
if self._choices_fn is not None:
items = list(self._choices_fn(state))
else:
items = list(self._static_choices)
if not items:
items = [ChoiceItem("", "(no options)", enabled=False, reason="No models discovered")]
self._choices = items
current_val = state.get(self.key)
original_val = current_val
found = False
for idx, item in enumerate(self._choices):
if item.value == current_val:
self._index = idx
found = True
break
if not found:
for idx, item in enumerate(self._choices):
if item.enabled:
self._index = idx
state[self.key] = item.value
if self._on_change is not None and item.value != original_val:
self._on_change(state, item)
found = True
break
if not found:
self._index = 0
state[self.key] = self._choices[0].value
def current(self, state: dict) -> ChoiceItem:
self._compute_choices(state)
return self._choices[self._index]
def handle_key(
self,
key: int,
state: dict,
stdscr: "curses._CursesWindow",
) -> Tuple[bool, Optional[str]]:
self._compute_choices(state)
count = len(self._choices)
if count == 0:
return False, None
if key in KEYS.NAV_LEFT:
for _ in range(count):
self._index = (self._index - 1) % count
if self._choices[self._index].enabled:
break
elif key in KEYS.NAV_RIGHT:
for _ in range(count):
self._index = (self._index + 1) % count
if self._choices[self._index].enabled:
break
state[self.key] = self._choices[self._index].value
if self._on_change is not None:
self._on_change(state, self._choices[self._index])
return False, None
def render(
self,
win: "curses._CursesWindow",
y: int,
width: int,
selected: bool,
state: dict,
) -> int:
self._compute_choices(state)
if self.default_value is None:
self.default_value = state.get(self.key, self._choices[self._index].value)
attr = curses.A_REVERSE if selected else curses.A_NORMAL
current = self._choices[self._index]
marker = "*" if self.is_modified(state) else " "
label = f"{marker}{self.icon} {self.name}: {current.label}"
win.addnstr(y, 2, label, max(10, width - 4), attr)
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
if not current.enabled and current.reason:
win.addnstr(
y + line_count,
6,
f"⚠ {current.reason}",
max(10, width - 8),
curses.color_pair(2) | curses.A_DIM,
)
line_count += 1
return line_count
def height(self, width: int, state: dict) -> int:
self._compute_choices(state)
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
return base
def get_value(self, state: dict):
self._compute_choices(state)
return state.get(self.key, self._choices[self._index].value)
def set_value(self, state: dict, value) -> None:
self._compute_choices(state)
for idx, item in enumerate(self._choices):
if item.value == value:
self._index = idx
state[self.key] = item.value
return
if self._choices:
state[self.key] = self._choices[self._index].value
def is_modified(self, state: dict) -> bool:
if self.default_value is None:
return False
return state.get(self.key) != self.default_value
class ActionOption(OptionBase):
def __init__(
self,
name: str,
description: str,
action: Callable[[dict], Tuple[bool, Optional[str]]],
*,
visible: Callable[[dict], bool] | None = None,
) -> None:
super().__init__(f"action:{name}", name, description, visible=visible)
self._action = action
self.icon = "[ACT]"
def render(
self,
win: "curses._CursesWindow",
y: int,
width: int,
selected: bool,
state: dict,
) -> int:
attr = curses.A_REVERSE if selected else curses.A_BOLD
label = f"{self.icon} {self.name}"
win.addnstr(y, 2, label, max(10, width - 4), attr)
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, state: dict) -> int:
wrap_width = max(10, width - 6)
return 1 + len(textwrap.wrap(self.description, wrap_width))
def handle_key(
self,
key: int,
state: dict,
stdscr: "curses._CursesWindow",
) -> Tuple[bool, Optional[str]]:
if key in KEYS.CONFIRM:
return self._action(state)
return False, None
def get_value(self, state: dict):
return None
def set_value(self, state: dict, value) -> None:
return
def is_modified(self, state: dict) -> bool:
return False
def shell_join(parts: Iterable[str]) -> str:
return " ".join(shlex.quote(str(x)) for x in parts)
def status_line(state: LoadModelDistState, ui_state: UIState) -> str:
status = state.status or ""
if ui_state.scanning:
frames = UI.SPINNER_FRAMES
frame = frames[int(time.time() * 4) % len(frames)]
scan_text = ui_state.scan_message or STRINGS["scan_start"]
if status and status != scan_text:
return f"{frame} {scan_text} | {status}"
return f"{frame} {scan_text}"
return status
def list_local_gguf(models_dir: Path) -> List[str]:
if not models_dir.exists() or not models_dir.is_dir():
return []
files = []
for path in models_dir.rglob("*.gguf"):
try:
rel = path.relative_to(models_dir)
except ValueError:
rel = path.name
files.append(str(rel))
return sorted(files)
def refresh_local_models(state: dict) -> Tuple[bool, Optional[str]]:
base = Path(state.get("models_dir") or str(MODELS_DIR)).expanduser()
try:
files = list_local_gguf(base)
except Exception as exc:
state["local_models"] = []
return False, f"Failed to scan models: {exc}"
state["local_models"] = files
if not files:
return False, "No GGUF models found in the selected directory."
return False, f"Found {len(files)} GGUF model(s)."
def build_local_choices(state: dict) -> List[ChoiceItem]:
models = state.get("local_models")
if models is None:
refresh_local_models(state)
models = state.get("local_models") or []
if not models:
return [ChoiceItem("", "No GGUF files discovered", enabled=False)]
return [ChoiceItem(m, m) for m in models]
def on_models_dir_change(state: dict, new_value: str) -> None:
state["models_dir"] = new_value or str(MODELS_DIR)
_, message = refresh_local_models(state)
state["status"] = message or ""
def set_model_from_choice(state: dict, choice: ChoiceItem) -> None:
if not choice.value:
return
base = Path(state.get("models_dir") or str(MODELS_DIR)).expanduser()
candidate = (base / choice.value).expanduser()
state["model_path"] = str(candidate)
state["selected_local_model"] = choice.value
def ensure_binary(path: Path) -> None:
if not path.exists():
raise FileNotFoundError(
f"{path} not found. Build llama.cpp with RPC support using autodevops (Enable distributed RPC backend)."
)
def parse_hosts(hosts: str) -> str:
entries = [h.strip() for h in hosts.split(",") if h.strip()]
if not entries:
raise ValueError("At least one RPC host must be provided (format: host:port).")
normalized: List[str] = []
for entry in entries:
host, sep, port = entry.rpartition(":")
if not sep:
raise ValueError(f"RPC host entry missing port: {entry}")
host = host.strip()
if not host:
raise ValueError(f"RPC host entry missing host: {entry}")
port_result = validate_port(port, default=None, name="RPC port")
if port_result.error or port_result.value is None:
detail = port_result.error or "Invalid RPC port"
raise ValueError(f"{detail} for host entry: {entry}")
normalized.append(f"{host}:{port_result.value}")
return ",".join(normalized)
def parse_int(
value: str | None,
*,
default: Optional[int] = None,
name: str = "value",
min_value: Optional[int] = None,
max_value: Optional[int] = None,
) -> int:
result = validate_int(
value,
default=default,
name=name,
min_value=min_value,
max_value=max_value,
)
if result.error:
raise ValueError(result.error)
return int(result.value)
def build_llama_command(state: dict) -> List[str]:
ensure_binary(LLAMA_CLI)
model_raw = (state.get("model_path") or "").strip()
if not model_raw:
raise ValueError("Model path is required.")
model_result = validate_path(model_raw, must_exist=True, name="Model path")
if model_result.error or model_result.value is None:
raise ValueError(model_result.error or "Model path is invalid.")
model = str(model_result.value)
host_list = parse_hosts(state.get("rpc_hosts", ""))
cmd: List[str] = [str(LLAMA_CLI), "-m", model, "--rpc", host_list]
ctx = state.get("ctx_size", "").strip()
if ctx:
ctx_int = parse_int(ctx, name="--ctx-size", min_value=1)
cmd += ["--ctx-size", str(ctx_int)]
ngl = state.get("n_gpu_layers", "").strip()
if ngl:
ngl_int = parse_int(ngl, name="-ngl", min_value=0)
cmd += ["-ngl", str(ngl_int)]
batch = state.get("batch_size", "").strip()
if batch:
batch_int = parse_int(batch, name="-b", min_value=1)
cmd += ["-b", str(batch_int)]
cache_dir = state.get("tensor_cache", "").strip()
if cache_dir:
cmd += ["-c", cache_dir]
extra = state.get("extra_flags", "").strip()
if extra:
extra_result = validate_split_extra_flags(extra)
if extra_result.error:
raise ValueError(extra_result.error)
cmd.extend(extra_result.value or [])
prompt_file = state.get("prompt_file", "").strip()
prompt_text = state.get("prompt_text", "").strip()
if prompt_file:
prompt_result = validate_path(prompt_file, must_exist=True, name="Prompt file")
if prompt_result.error or prompt_result.value is None:
raise ValueError(prompt_result.error or "Prompt file is invalid.")
cmd += ["-f", str(prompt_result.value)]
elif prompt_text:
cmd += ["-p", prompt_text]
return cmd
def build_rpc_command(state: dict) -> List[str]:
ensure_binary(RPC_SERVER)
port_result = validate_port(state.get("worker_port"), default=int(DEFAULT_RPC_PORT), name="RPC port")
if port_result.error or port_result.value is None:
raise ValueError(port_result.error or "Invalid RPC port")
port = str(port_result.value)
host = (state.get("worker_host") or "0.0.0.0").strip() or "0.0.0.0"
cmd: List[str] = [str(RPC_SERVER), "-p", port, "--host", host]
cache = state.get("worker_cache", "").strip()
if cache:
cmd += ["-c", cache]
return cmd
def build_cuda_visible_devices(value: str | None) -> tuple[Optional[str], Optional[str]]:
gpus_all = memory_utils.detect_gpus()
indices, err = memory_utils.parse_device_list(value, gpus_all)
if err:
return None, err
if indices is None:
return None, None
if not indices:
return "", None
return ",".join(str(idx) for idx in indices), None
def start_worker_process(state: LoadModelDistState) -> subprocess.Popen:
cmd = build_rpc_command(state)
env = os.environ.copy()
cuda_devices, err = build_cuda_visible_devices(state.get("worker_devices"))
if err:
raise RuntimeError(err)
if cuda_devices is not None:
env["CUDA_VISIBLE_DEVICES"] = cuda_devices
try:
proc = subprocess.Popen(cmd, env=env)
except FileNotFoundError as exc:
raise FileNotFoundError(str(exc)) from exc
except Exception as exc:
raise RuntimeError(f"Failed to start rpc-server: {exc}") from exc
return register_process(proc)
def merge_hosts(state: dict, hosts: Iterable[str]) -> None:
new_hosts = {h.strip() for h in hosts if h.strip()}
if not new_hosts:
return
existing = {h.strip() for h in state.get("rpc_hosts", "").split(",") if h.strip()}
combined = sorted(existing | new_hosts)
state["rpc_hosts"] = ",".join(combined)
discovered = {h.strip() for h in state.get("discovered_hosts", []) if h.strip()}
state["discovered_hosts"] = sorted(discovered | new_hosts)
def _list_private_networks() -> Tuple[List[ipaddress.IPv4Network], List[str]]:
networks: List[ipaddress.IPv4Network] = []
local_ips: List[str] = []
try:
output = subprocess.check_output(
["ip", "-o", "-f", "inet", "addr", "show"],
text=True,
stderr=subprocess.DEVNULL,
)
except Exception:
return networks, local_ips
for line in output.splitlines():
parts = line.split()
if len(parts) < 4:
continue
cidr = parts[3]
try:
iface = ipaddress.ip_interface(cidr)
except ValueError:
continue
ip = iface.ip
if ip.is_loopback or not ip.is_private:
continue
network = iface.network
if network.num_addresses > 256:
network = ipaddress.ip_network(f"{ip}/24", strict=False)
networks.append(network)
local_ips.append(str(ip))
# dedupe networks
uniq = []
seen = set()
for net in networks:
if net.network_address not in seen:
uniq.append(net)
seen.add(net.network_address)
return uniq, local_ips
def discover_network_workers(port: str, timeout: float = UI.SCAN_TIMEOUT) -> List[str]:
port_result = validate_port(port, default=None, name="RPC port")
if port_result.error or port_result.value is None:
return []
port_int = int(port_result.value)
networks, local_ips = _list_private_networks()
if not networks:
return []
local_set = set(local_ips)
discovered: List[str] = []
lock = threading.Lock()
def probe(ip: ipaddress.IPv4Address) -> None:
addr = str(ip)
if addr in local_set:
return
try:
with socket.create_connection((addr, port_int), timeout=timeout):
with lock:
discovered.append(f"{addr}:{port}")
except (socket.timeout, OSError):
pass
with ThreadPoolExecutor(max_workers=128) as executor:
for network in networks:
for host in network.hosts():
executor.submit(probe, host)
return sorted(set(discovered))
def start_network_scan(state: LoadModelDistState, ui_state: UIState) -> None:
if ui_state.scanning:
return
port_result = validate_port(state.worker_port, default=None, name="RPC port")
if port_result.error or port_result.value is None:
state.status = port_result.error or "Invalid RPC port"
append_log(ui_state, state.status)
return
port_str = str(port_result.value)
ui_state.scanning = True
ui_state.scan_message = STRINGS["scan_start"]
ui_state.scan_start = time.time()
append_log(ui_state, STRINGS["scan_start"])
def scan_thread() -> None:
try:
discovered = discover_network_workers(port_str)
if discovered:
merge_hosts(state, discovered)
msg = f"Discovered {len(discovered)} worker(s) on port {port_str}."
else:
msg = f"No rpc-server instances found on port {port_str}."
state.status = msg
append_log(ui_state, msg)
finally:
elapsed = max(time.time() - (ui_state.scan_start or time.time()), 0.01)
append_log(ui_state, f"{STRINGS['scan_complete']} ({elapsed:.1f}s)")
ui_state.scanning = False
ui_state.scan_message = ""
ui_state.scan_start = None
threading.Thread(target=scan_thread, daemon=True).start()
def action_launch(state: dict) -> Tuple[bool, Optional[str]]:
messages: List[str] = []
if state.get("local_worker"):
proc = state.get("worker_process")
if proc and proc.poll() is not None:
unregister_process(proc)
state["worker_process"] = None
proc = None
if not proc or proc.poll() is not None:
try:
proc = start_worker_process(state)
state["worker_process"] = proc