-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathRouter.py
More file actions
2054 lines (1843 loc) · 76.6 KB
/
Router.py
File metadata and controls
2054 lines (1843 loc) · 76.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
"""Router/load-balancer support for ezlocalai.
Two pieces live here:
1. ``WorkerRegistry`` + ``Router`` — used by the router process to keep track of
worker ezlocalai instances that have registered themselves and to pick the
best worker for a given request.
2. ``WorkerHeartbeatClient`` — used by every worker ezlocalai instance to
register and heartbeat with a router (when ``ROUTER_URL`` is set).
The router exposes the same OpenAI-compatible API surface as a normal
ezlocalai server but does no inference itself. It selects a worker based on:
* Capability match (text / vision / voice / image / video / embedding)
* Whether the worker has the requested model
* Free VRAM and queue depth (more free, less queued = better score)
* Liveness (recent heartbeat)
The worker → router protocol is intentionally tiny: a ``register`` on startup,
periodic ``heartbeat`` POSTs, and a best-effort ``deregister`` on shutdown.
"""
from __future__ import annotations
import asyncio
import logging
import os
import re
import socket
import subprocess
import time
import uuid
from dataclasses import dataclass, field
from threading import RLock
from typing import Any, Dict, List, Optional, Tuple
import aiohttp
from Globals import getenv
from Tunnel import is_tunnel_url
# ---------------------------------------------------------------------------
# Capability detection
# ---------------------------------------------------------------------------
ALL_CAPABILITIES = {"text", "vision", "tts", "stt", "image", "video", "embedding"}
MODEL_STRICT_CAPABILITIES = {"text", "vision"}
_RUNTIME_VERSION_CACHE: Optional[str] = None
def is_mtp_model_name(model_name: Optional[str]) -> bool:
"""Return True for model names that advertise an MTP variant."""
return "-mtp" in _formatless_model_basename(model_name)
def _formatless_model_basename(model_name: Optional[str]) -> str:
"""Lowercase model basename without repo, quant format, or replica suffix."""
if not model_name:
return ""
name = str(model_name).strip()
if "@" in name:
name = name.rsplit("@", 1)[0]
if "#" in name:
name = name.split("#", 1)[0]
name = name.split("/")[-1].lower()
for suffix in ("-gguf", ".gguf"):
if name.endswith(suffix):
name = name[: -len(suffix)]
break
return name
def _model_family_key(model_name: Optional[str]) -> str:
"""Canonical model family key where MTP/non-MTP variants are compatible."""
base = _formatless_model_basename(model_name)
if not base:
return ""
return base.replace("-mtp", "")
def _model_name_matches(requested: Optional[str], served: Optional[str]) -> bool:
"""Return True when a served model is compatible with the requested model.
A base/non-MTP request can run on an MTP model of the same family. An
explicit MTP request still requires an MTP model to count as a same-model
match; broader cross-model fallback happens later in the router.
"""
if not requested:
return True
if not served:
return False
req = str(requested).strip().lower()
srv = str(served).strip().lower()
req_short = _formatless_model_basename(requested)
srv_short = _formatless_model_basename(served)
if req == srv or (req_short and req_short == srv_short):
return True
req_family = _model_family_key(requested)
srv_family = _model_family_key(served)
if req_family and srv_family and req_family == srv_family:
if is_mtp_model_name(requested) and not is_mtp_model_name(served):
return False
return True
# Preserve the router's historical loose alias behavior: a short model name
# such as "Qwen3.6-35B-A3B" should match a full HF repo id.
return bool(req_short and req_short in srv)
def _clean_version(value: Optional[str]) -> str:
value = (value or "").strip()
if not value or value.lower() in {"none", "null", "unknown", "undefined"}:
return ""
return value[:80]
def _read_first_line(path: str) -> str:
try:
with open(path, encoding="utf-8", errors="replace") as fh:
return fh.readline().strip()
except Exception:
return ""
def _version_from_packed_refs(packed_refs_path: str, ref: str) -> str:
try:
with open(packed_refs_path, encoding="utf-8", errors="replace") as fh:
for line in fh:
line = line.strip()
if not line or line.startswith("#") or line.startswith("^"):
continue
parts = line.split()
if len(parts) >= 2 and parts[1] == ref:
return parts[0]
except Exception:
pass
return ""
def _version_from_git_metadata(repo_dir: str) -> str:
"""Read a short commit SHA from lightweight .git metadata.
Docker images intentionally exclude .git objects, but keeping HEAD, refs,
and packed-refs is enough for dashboard version reporting.
"""
git_dir = os.path.join(repo_dir, ".git")
if os.path.isfile(git_dir):
git_file = _read_first_line(git_dir)
if git_file.startswith("gitdir:"):
git_dir = git_file.split(":", 1)[1].strip()
if not os.path.isabs(git_dir):
git_dir = os.path.normpath(os.path.join(repo_dir, git_dir))
if not os.path.isdir(git_dir):
return ""
head = _read_first_line(os.path.join(git_dir, "HEAD"))
if not head:
return ""
sha = head
if head.startswith("ref:"):
ref = head.split(":", 1)[1].strip()
sha = _read_first_line(os.path.normpath(os.path.join(git_dir, ref)))
if not sha:
sha = _version_from_packed_refs(os.path.join(git_dir, "packed-refs"), ref)
if re.fullmatch(r"[0-9a-fA-F]{7,40}", sha or ""):
return sha[:7].lower()
return ""
def get_runtime_version(repo_dir: Optional[str] = None) -> str:
"""Best-effort runtime version shown by the router dashboard."""
global _RUNTIME_VERSION_CACHE
if repo_dir is None and _RUNTIME_VERSION_CACHE is not None:
return _RUNTIME_VERSION_CACHE
repo_dir = repo_dir or os.path.dirname(os.path.abspath(__file__))
for env_name in ("EZLOCALAI_VERSION", "EZLOCALAI_COMMIT", "GIT_COMMIT"):
version = _clean_version(os.getenv(env_name))
if version:
if repo_dir == os.path.dirname(os.path.abspath(__file__)):
_RUNTIME_VERSION_CACHE = version
return version
for filename in (".ezlocalai-version", "VERSION"):
version = _clean_version(_read_first_line(os.path.join(repo_dir, filename)))
if version:
if repo_dir == os.path.dirname(os.path.abspath(__file__)):
_RUNTIME_VERSION_CACHE = version
return version
try:
result = subprocess.run(
["git", "-C", repo_dir, "rev-parse", "--short", "HEAD"],
capture_output=True,
text=True,
timeout=3,
)
if result.returncode == 0:
version = _clean_version(result.stdout)
if version:
if repo_dir == os.path.dirname(os.path.abspath(__file__)):
_RUNTIME_VERSION_CACHE = version
return version
except Exception:
pass
version = _version_from_git_metadata(repo_dir)
if version:
if repo_dir == os.path.dirname(os.path.abspath(__file__)):
_RUNTIME_VERSION_CACHE = version
return version
try:
from importlib.metadata import PackageNotFoundError, version as pkg_version
try:
version = _clean_version(pkg_version("ezlocalai"))
except PackageNotFoundError:
version = ""
if version:
if repo_dir == os.path.dirname(os.path.abspath(__file__)):
_RUNTIME_VERSION_CACHE = version
return version
except Exception:
pass
if repo_dir == os.path.dirname(os.path.abspath(__file__)):
_RUNTIME_VERSION_CACHE = ""
return ""
def _usable_context_from_config(
max_tokens_value: Any, n_parallel_value: Any = 1
) -> int:
try:
max_tokens = int(max_tokens_value or 0)
except (TypeError, ValueError):
return 0
if max_tokens <= 0:
return 0
try:
if n_parallel_value is None or n_parallel_value == "":
n_parallel = 1
else:
n_parallel = int(n_parallel_value)
except (TypeError, ValueError):
n_parallel = 1
if n_parallel == 0:
n_parallel = min(max(1, max_tokens // 32768), 16)
if n_parallel < 1:
n_parallel = 1
return max(1, max_tokens // n_parallel)
def _resolve_public_model_name(pipe: Any, model_name: str) -> str:
if pipe is not None:
try:
resolver = getattr(pipe, "_resolve_source_model", None)
if resolver is not None:
return str(resolver(model_name))
except Exception:
pass
if "#" in model_name:
return model_name.split("#", 1)[0]
return model_name
def _configured_contexts_from_pipe(pipe: Any) -> Dict[str, int]:
contexts: Dict[str, int] = {}
if pipe is None:
return contexts
available_models = list(getattr(pipe, "available_models", []) or [])
model_configs = dict(getattr(pipe, "model_configs", {}) or {})
for model_id in available_models:
cfg = model_configs.get(model_id, {}) or {}
context = _usable_context_from_config(
cfg.get("max_tokens"), cfg.get("n_parallel", 1)
)
if context <= 0:
continue
public_name = _resolve_public_model_name(pipe, str(model_id))
contexts[public_name] = max(contexts.get(public_name, 0), context)
return contexts
def _split_env_csv(key: str, default: str) -> List[str]:
value = getenv(key, default)
return [part.strip() for part in str(value or "").split(",") if part.strip()]
def _csv_value(values: List[str], index: int, default: str) -> str:
if index < len(values):
return values[index]
if values:
return values[-1]
return default
def _configured_contexts_from_env() -> Dict[str, int]:
contexts: Dict[str, int] = {}
model_entries = _split_env_csv("DEFAULT_MODEL", "")
max_tokens = _split_env_csv("LLM_MAX_TOKENS", "65536")
n_parallels = _split_env_csv("N_PARALLEL", "1")
for index, model_name in enumerate(model_entries):
if "@" in model_name:
model_name = model_name.rsplit("@", 1)[0]
if not model_name or model_name.lower() == "none":
continue
context = _usable_context_from_config(
_csv_value(max_tokens, index, "65536"),
_csv_value(n_parallels, index, "1"),
)
if context > 0:
contexts[model_name] = max(contexts.get(model_name, 0), context)
return contexts
def configured_model_contexts(pipe: Any = None) -> Dict[str, int]:
contexts = _configured_contexts_from_pipe(pipe)
if contexts:
return contexts
return _configured_contexts_from_env()
def detect_local_capabilities() -> List[str]:
"""Best-effort guess at what this ezlocalai instance can serve.
Reads the same env vars the rest of the app uses so a worker advertises
itself accurately based on its existing config (no extra env required).
Important semantic of the *_SERVER env vars (matches Globals.py docs):
"" → load locally on demand (this worker provides the capability)
"true" → this worker IS a dedicated server for that capability
URL → this worker DELEGATES that capability to a remote server,
so it should NOT advertise the capability itself.
"""
caps: List[str] = []
default_model = (getenv("DEFAULT_MODEL") or "").strip()
voice_server = (getenv("VOICE_SERVER") or "").strip().lower()
image_server = (getenv("IMAGE_SERVER") or "").strip().lower()
text_server = (getenv("TEXT_SERVER") or "").strip().lower()
embedding_server = (getenv("EMBEDDING_SERVER") or "").strip().lower()
img_model = (getenv("IMG_MODEL") or "").strip().lower()
video_model = (getenv("VIDEO_MODEL") or "").strip().lower()
tts_enabled = (getenv("TTS_ENABLED") or "true").strip().lower() == "true"
stt_enabled = (getenv("STT_ENABLED") or "true").strip().lower() == "true"
image_enabled = (getenv("IMAGE_ENABLED") or "false").strip().lower() == "true"
video_enabled = (getenv("VIDEO_ENABLED") or "false").strip().lower() == "true"
embedding_enabled = (
getenv("EMBEDDING_ENABLED") or "true"
).strip().lower() == "true"
def _is_url(v: str) -> bool:
return v.startswith("http://") or v.startswith("https://")
voice_delegated = _is_url(voice_server)
image_delegated = _is_url(image_server)
text_delegated = _is_url(text_server)
embedding_delegated = _is_url(embedding_server)
is_dedicated_image = image_server == "true"
# Text/vision: any worker that has DEFAULT_MODEL loaded can answer text,
# *unless* it's explicitly delegating text elsewhere. Even dedicated
# voice/image servers may also serve text if they loaded an LLM, so we
# no longer exclude them here.
if default_model and default_model.lower() != "none" and not text_delegated:
caps.append("text")
lowered = default_model.lower()
is_vision = any(
tag in lowered
for tag in (
"-vl",
"-vlm",
"vision",
"qwen3.6",
"qvq",
"minicpm-v",
"llava",
"bakllava",
"moondream",
"cogvlm",
"internvl",
"idefics",
)
)
# Definitive check: mmproj file exists on disk for this model
if not is_vision:
try:
model_basename = default_model.split("/")[-1].split("-GGUF")[0]
model_dir = os.path.join("models", model_basename)
if os.path.isdir(model_dir):
is_vision = any(
"mmproj" in f.lower() and f.endswith(".gguf")
for f in os.listdir(model_dir)
)
except Exception:
pass
if is_vision:
caps.append("vision")
elif (
text_server == "true"
and "text" not in caps
and default_model
and default_model.lower() != "none"
):
caps.append("text")
# TTS: claim if we serve speech synthesis locally.
if not voice_delegated and tts_enabled:
caps.append("tts")
# STT: claim if we serve transcription locally.
if not voice_delegated and stt_enabled:
caps.append("stt")
# Image: claim it only if we actually generate locally — img_model set or
# this is a dedicated image server, and we're not delegating elsewhere.
if (
image_enabled
and not image_delegated
and ((img_model and img_model not in ("none", "")) or is_dedicated_image)
):
caps.append("image")
if (
video_enabled
and not image_delegated
and video_model
and video_model not in ("none", "")
):
caps.append("video")
if embedding_enabled and not embedding_delegated:
caps.append("embedding")
# De-dup, preserve order
seen = set()
deduped = []
for c in caps:
if c not in seen:
seen.add(c)
deduped.append(c)
return deduped
# ---------------------------------------------------------------------------
# Hardware tier scoring
# ---------------------------------------------------------------------------
# Higher tier = faster inference. Used to break ties when load is similar so
# requests prefer the 5090 over the 4090 over the 3090, etc. Unrecognized GPUs
# get TIER_DEFAULT_GPU; CPU-only workers get TIER_CPU.
# Substring match (case-insensitive) on torch's get_device_name() output.
GPU_TIERS: List[Tuple[str, int]] = [
# Datacenter / Hopper / Blackwell
("h200", 100),
("h100", 95),
("b200", 110),
("a100", 80),
("a6000", 70),
("a40", 65),
("l40", 70),
# RTX 50-series (Blackwell)
("5090", 90),
("5080", 75),
("5070 ti", 60),
("5070", 55),
("5060", 40),
# RTX 40-series (Ada Lovelace)
("4090", 80),
("4080 super", 65),
("4080", 60),
("4070 ti super", 55),
("4070 ti", 50),
("4070", 45),
("4060 ti", 35),
("4060", 30),
# RTX 30-series (Ampere)
("3090 ti", 55),
("3090", 50),
("3080 ti", 45),
("3080", 40),
("3070 ti", 32),
("3070", 30),
("3060 ti", 25),
("3060", 22),
# RTX 20-series (Turing)
("2080 ti", 28),
("2080", 22),
("2070", 18),
("2060", 15),
# GTX
("1080 ti", 14),
("1080", 12),
("1070", 10),
# Jetson (ordered most → least powerful; match "orin nx" before generic "orin")
("agx orin", 35),
("orin nx 16g", 25),
("orin nx", 22),
("orin nano", 12),
("orin", 20),
("agx xavier", 16),
("xavier nx 16g", 14),
("xavier nx", 12),
("xavier", 10),
("tx2", 6),
("nano", 4),
# AMD Instinct (datacenter)
("mi300x", 90),
("mi300", 85),
("mi250x", 70),
("mi250", 65),
("mi210", 55),
("mi100", 45),
# AMD Radeon RX
("rx 7900 xtx", 55),
("rx 7900 xt", 50),
("rx 7900", 48),
("rx 7800", 38),
("rx 7700", 30),
("rx 7600", 22),
("rx 6950", 42),
("rx 6900", 38),
("rx 6800", 32),
("rx 6700", 25),
("rx 6600", 18),
# AMD Ryzen integrated / APU
("radeon 780m", 8),
("radeon 760m", 6),
("radeon 680m", 5),
("radeon", 4),
# Apple Silicon
("m4 max", 50),
("m4 ultra", 65),
("m4 pro", 35),
("m4", 25),
("m3 ultra", 45),
("m3 max", 38),
("m3 pro", 28),
("m3", 20),
("m2 ultra", 40),
("m2 max", 32),
("m2 pro", 22),
("m2", 16),
("m1 ultra", 30),
("m1 max", 25),
("m1 pro", 18),
("m1", 12),
# Hailo NPU (Raspberry Pi AI HAT)
("hailo-8l", 6),
("hailo-8", 8),
("hailo", 5),
# Generic Intel
("arc a770", 18),
("arc a750", 14),
("arc a380", 8),
("arc", 6),
("xe", 4),
]
TIER_DEFAULT_GPU = 20
TIER_CPU = 2 # CPU-only is legitimate; score above 1 so it isn't penalised as broken
TIER_NPU = 5 # Hailo/NPU category when device detection finds it without VRAM info
TUNNEL_TIER_PENALTY = 5
def gpu_tier_for_name(name: str) -> int:
"""Look up a hardware tier score from a GPU model name string."""
if not name:
return TIER_CPU
lname = name.lower()
for needle, tier in GPU_TIERS:
if needle in lname:
return tier
return TIER_DEFAULT_GPU
def detect_local_gpus() -> List[Dict[str, Any]]:
"""Best-effort enumeration of local accelerators: CUDA, ROCm, MPS, Hailo, CPU.
Returns a list of dicts with keys: index, name, total_vram_gb, tier, backend.
Always returns at least one entry (CPU fallback) so workers are never
invisible to the router.
"""
gpus: List[Dict[str, Any]] = []
# --- CUDA (NVIDIA) and ROCm (AMD) via PyTorch ---
try:
import torch # type: ignore
if torch.cuda.is_available():
backend = "rocm" if getattr(torch.version, "hip", None) else "cuda"
for i in range(torch.cuda.device_count()):
try:
props = torch.cuda.get_device_properties(i)
name = props.name
total_gb = float(props.total_memory) / (1024**3)
except Exception:
name = f"{backend}:{i}"
total_gb = 0.0
gpus.append(
{
"index": i,
"name": name,
"total_vram_gb": round(total_gb, 2),
"tier": gpu_tier_for_name(name),
"backend": backend,
}
)
except Exception as e:
logging.debug(f"[Router] CUDA/ROCm enumeration failed: {e}")
# --- Apple Silicon MPS ---
if not gpus:
try:
import torch # type: ignore
if torch.backends.mps.is_available():
import platform
chip = platform.processor() or "Apple Silicon"
# Try to get unified memory size via sysctl
total_gb = 0.0
try:
import subprocess
out = subprocess.check_output(
["sysctl", "-n", "hw.memsize"], timeout=3
)
total_gb = int(out.strip()) / (1024**3)
except Exception:
pass
name = chip if chip else "Apple Silicon"
gpus.append(
{
"index": 0,
"name": name,
"total_vram_gb": round(total_gb, 2),
"tier": gpu_tier_for_name(name),
"backend": "mps",
}
)
except Exception as e:
logging.debug(f"[Router] MPS enumeration failed: {e}")
# --- Hailo NPU (Raspberry Pi AI HAT 2+ and Hailo-8/8L PCIe cards) ---
if not gpus:
try:
import glob
import subprocess
hailo_devs = glob.glob("/dev/hailo*")
if hailo_devs:
# Try hailortcli for device info
try:
out = subprocess.check_output(
["hailortcli", "scan"], timeout=5, stderr=subprocess.DEVNULL
).decode(errors="replace")
# Extract model name from output, e.g. "Hailo-8L"
import re as _re
m = _re.search(r"(Hailo-\w+)", out, _re.IGNORECASE)
chip = m.group(1) if m else "Hailo NPU"
except Exception:
chip = f"Hailo NPU ({len(hailo_devs)} device(s))"
gpus.append(
{
"index": 0,
"name": chip,
"total_vram_gb": 0.0, # Hailo uses on-chip SRAM, not VRAM
"tier": gpu_tier_for_name(chip),
"backend": "hailo",
}
)
except Exception as e:
logging.debug(f"[Router] Hailo enumeration failed: {e}")
# --- AMD GPU via rocm-smi (fallback when PyTorch ROCm not installed) ---
if not gpus:
try:
import subprocess
out = subprocess.check_output(
["rocm-smi", "--showproductname", "--csv"],
timeout=5,
stderr=subprocess.DEVNULL,
).decode(errors="replace")
import re as _re
for i, line in enumerate(out.splitlines()):
if i == 0 or not line.strip():
continue
# CSV: GPU_ID,Card_Series,...
parts = [p.strip().strip('"') for p in line.split(",")]
name = parts[1] if len(parts) > 1 else f"AMD GPU {i}"
gpus.append(
{
"index": i - 1,
"name": name,
"total_vram_gb": 0.0,
"tier": gpu_tier_for_name(name),
"backend": "rocm",
}
)
except Exception as e:
logging.debug(f"[Router] rocm-smi enumeration failed: {e}")
# --- Jetson / Tegra (unified memory; CUDA may be unavailable inside the container) ---
# Detect via /proc/device-tree/model which is always present on Jetson boards.
if not gpus:
try:
with open("/proc/device-tree/model") as _f:
_model = _f.read().rstrip("\x00").strip()
if "jetson" in _model.lower() or "tegra" in _model.lower():
_jtier = gpu_tier_for_name(_model)
# Unified memory — report it as "VRAM" so the dashboard shows it
_jtotal = 0.0
try:
import psutil as _ps
_jtotal = _ps.virtual_memory().total / (1024**3)
except Exception:
try:
with open("/proc/meminfo") as _mf:
for _line in _mf:
if _line.startswith("MemTotal"):
_jtotal = int(_line.split()[1]) / (1024**2)
break
except Exception:
pass
gpus.append(
{
"index": 0,
"name": _model,
"total_vram_gb": round(_jtotal, 2),
"tier": _jtier,
"backend": "cuda",
}
)
except Exception as _e:
logging.debug(f"[Router] Jetson detection failed: {_e}")
# --- CPU-only fallback ---
# Always include a CPU entry so the router sees compute even on CPU workers.
# We add it as a supplemental entry only; if real accelerators were found we
# still keep them.
try:
import platform
cpu_name = platform.processor() or platform.machine() or "CPU"
# On Pi, machine() gives 'aarch64'; enrich with /proc/cpuinfo model name
try:
with open("/proc/cpuinfo") as f:
for line in f:
if line.lower().startswith("model name") or line.lower().startswith(
"hardware"
):
val = line.split(":", 1)[-1].strip()
if val:
cpu_name = val
break
except Exception:
pass
gpus.append(
{
"index": -1,
"name": cpu_name,
"total_vram_gb": 0.0,
"tier": TIER_CPU,
"backend": "cpu",
}
)
except Exception as e:
logging.debug(f"[Router] CPU fallback failed: {e}")
return gpus
def best_gpu_tier(gpus: List[Dict[str, Any]]) -> int:
"""The best accelerator tier on this worker.
Excludes the CPU fallback entry (index -1) from the max so that a worker
with a real GPU isn't dragged down, but a CPU-only worker still gets
TIER_CPU from the CPU entry.
"""
accel = [g for g in gpus if g.get("index", 0) >= 0]
if accel:
return max(int(g.get("tier", TIER_DEFAULT_GPU)) for g in accel)
# CPU-only worker
cpu = [g for g in gpus if g.get("backend") == "cpu"]
return int(cpu[0]["tier"]) if cpu else TIER_CPU
# ---------------------------------------------------------------------------
# Worker registry (router-side)
# ---------------------------------------------------------------------------
@dataclass
class WorkerInfo:
worker_id: str
label: str
url: str
api_key: str = "" # Key router should use when calling the worker
capabilities: List[str] = field(default_factory=list)
models: List[str] = field(default_factory=list)
# Live state, updated each heartbeat
free_vram_gb: float = 0.0
total_vram_gb: float = 0.0
free_ram_gb: float = 0.0
total_ram_gb: float = 0.0
queue_depth: int = 0
queue_capacity: int = 1
in_flight: int = 0
# Exact per-capability and per-model slot state from worker heartbeats.
# Shape: {"text": {"capacity": 8, "in_flight": 2, "queued": 0, "available": 6}}
cap_slots: Dict[str, Dict[str, int]] = field(default_factory=dict)
model_slots: Dict[str, Dict[str, int]] = field(default_factory=dict)
# Hardware introspection (auto-reported by the worker)
gpus: List[Dict[str, Any]] = field(default_factory=list)
best_tier: int = TIER_CPU
# Per-model context window (max_tokens). Auto-reported when available.
model_context: Dict[str, int] = field(default_factory=dict)
# Per-model quantization (e.g. "Q4_K_XL"). Auto-reported when available.
model_quant: Dict[str, str] = field(default_factory=dict)
# Capability-specific model names: {"tts": "Chatterbox TTS", "stt": "Whisper large-v3", ...}
cap_models: Dict[str, str] = field(default_factory=dict)
last_heartbeat: float = field(default_factory=time.time)
registered_at: float = field(default_factory=time.time)
extra: Dict[str, Any] = field(default_factory=dict)
# Consecutive connection failures from the router side (not the worker heartbeat)
connection_failures: int = 0
# Runtime version identifier of the ezlocalai code running on this worker.
version: str = ""
# Recent error events (sliding window; capped). Each entry:
# {ts, kind, status, path, message}
recent_errors: List[Dict[str, Any]] = field(default_factory=list)
# Cumulative count of all errors seen since registration
total_errors: int = 0
# Circuit breaker: when open, the worker is excluded from selection
# until ``circuit_open_until`` (epoch seconds) passes.
circuit_open_until: float = 0.0
def to_public(self) -> Dict[str, Any]:
return {
"worker_id": self.worker_id,
"label": self.label,
"url": self.url,
"capabilities": list(self.capabilities),
"models": list(self.models),
"free_vram_gb": self.free_vram_gb,
"total_vram_gb": self.total_vram_gb,
"free_ram_gb": self.free_ram_gb,
"total_ram_gb": self.total_ram_gb,
"queue_depth": self.queue_depth,
"queue_capacity": self.queue_capacity,
"in_flight": self.in_flight,
"cap_slots": dict(self.cap_slots),
"model_slots": dict(self.model_slots),
"slot_total_capacity": self.total_capacity(),
"slot_total_busy": self.total_busy(),
"slot_total_available": self.total_slots_left(),
"gpus": list(self.gpus),
"best_tier": self.best_tier,
"priority_tier": self.priority_tier,
"model_context": dict(self.model_context),
"model_quant": dict(self.model_quant),
"cap_models": dict(self.cap_models),
"age_seconds": time.time() - self.registered_at,
"last_heartbeat_age": time.time() - self.last_heartbeat,
"version": self.version,
"connection_failures": self.connection_failures,
"total_errors": self.total_errors,
"recent_errors": list(self.recent_errors),
"circuit_open_until": self.circuit_open_until,
"circuit_open": self.is_circuit_open(),
"extra": self.extra,
}
def is_circuit_open(self) -> bool:
return time.time() < self.circuit_open_until
def is_alive(self, ttl: float) -> bool:
return (time.time() - self.last_heartbeat) <= ttl
@staticmethod
def _normalize_slot(
raw: Optional[Dict[str, Any]], fallback_capacity: int = 1
) -> Dict[str, int]:
raw = raw or {}
capacity = max(0, int(raw.get("capacity", fallback_capacity) or 0))
in_flight = max(0, int(raw.get("in_flight", 0) or 0))
queued = max(0, int(raw.get("queued", 0) or 0))
return {
"capacity": capacity,
"in_flight": in_flight,
"queued": queued,
"available": max(0, capacity - in_flight - queued),
}
@staticmethod
def _match_name(
name: Optional[str], slot_map: Dict[str, Dict[str, int]]
) -> Optional[str]:
if not name or not slot_map:
return None
if name in slot_map:
return name
base = name.split("/")[-1].lower()
for key in slot_map:
if key.lower() == name.lower() or key.split("/")[-1].lower() == base:
return key
for key in slot_map:
if _model_name_matches(name, key):
return key
for key in slot_map:
if base and base in key.lower():
return key
return None
def slot_state(
self, capability: Optional[str] = None, model: Optional[str] = None
) -> Dict[str, int]:
"""Return the most specific live slot state for a route decision."""
if model:
model_key = self._match_name(model, self.model_slots)
if model_key:
return self._normalize_slot(self.model_slots.get(model_key))
if capability:
if capability in self.cap_slots:
return self._normalize_slot(self.cap_slots.get(capability))
if capability == "vision" and "text" in self.cap_slots:
return self._normalize_slot(self.cap_slots.get("text"))
fallback_capacity = max(1, int(self.queue_capacity or 1))
if capability in ("image", "stt", "video", "tts"):
fallback_capacity = 1
busy = self.effective_busy()
return self._normalize_slot(
{
"capacity": fallback_capacity,
"in_flight": min(busy, fallback_capacity),
"queued": max(0, busy - fallback_capacity),
},
fallback_capacity=fallback_capacity,
)
def effective_busy(
self, capability: Optional[str] = None, model: Optional[str] = None
) -> int:
"""Best estimate of in-flight work right now.
``queue_depth`` only refreshes on heartbeat (every ~10s) so during a
burst it lags reality. ``in_flight`` is incremented synchronously by
the proxy as soon as a request is dispatched, so it's the freshest
signal between heartbeats. We take the max so neither source can
under-count actual load.
"""
if capability or model:
state = self.slot_state(capability=capability, model=model)
return int(state.get("in_flight", 0)) + int(state.get("queued", 0))
return max(int(self.queue_depth), int(self.in_flight))
def capacity_for(
self, capability: Optional[str] = None, model: Optional[str] = None
) -> int:
return int(
self.slot_state(capability=capability, model=model).get("capacity", 0)
)
def slots_left(
self, capability: Optional[str] = None, model: Optional[str] = None
) -> int:
state = self.slot_state(capability=capability, model=model)
return max(
0,
int(state.get("capacity", 0))
- int(state.get("in_flight", 0))
- int(state.get("queued", 0)),
)
def has_capacity(
self, capability: Optional[str] = None, model: Optional[str] = None
) -> bool:
# A worker is considered "free" if it has at least one open slot,
# using whichever busy-signal is higher (router-side in-flight or
# last heartbeat queue depth).
return self.slots_left(capability=capability, model=model) > 0
def total_capacity(self) -> int: