-
Notifications
You must be signed in to change notification settings - Fork 866
Expand file tree
/
Copy pathworker.py
More file actions
2090 lines (1883 loc) · 83.9 KB
/
Copy pathworker.py
File metadata and controls
2090 lines (1883 loc) · 83.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2022-2023 XProbe Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import logging
import os
import pathlib
import platform
import queue
import shutil
import signal
import sys
import threading
import time
from collections import defaultdict
from dataclasses import dataclass, field
from logging import getLogger
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Literal,
Optional,
Set,
Tuple,
Type,
Union,
no_type_check,
)
import xoscar as xo
from async_timeout import timeout
from xoscar import MainActorPoolType
from ..constants import (
XINFERENCE_ALLOW_MULTI_REPLICA_PER_GPU,
XINFERENCE_CACHE_DIR,
XINFERENCE_DISABLE_HEALTH_CHECK,
XINFERENCE_DISABLE_METRICS,
XINFERENCE_ENABLE_VIRTUAL_ENV,
XINFERENCE_HEALTH_CHECK_INTERVAL,
XINFERENCE_HEALTH_CHECK_TIMEOUT,
XINFERENCE_VIRTUAL_ENV_DIR,
XINFERENCE_VIRTUAL_ENV_SKIP_INSTALLED,
)
from ..core.model import ModelActor
from ..core.status_guard import LaunchStatus
from ..device_utils import get_available_device_env_name, gpu_count
from ..model.core import VirtualEnvSettings, create_model_instance
from ..model.utils import CancellableDownloader, get_engine_params_by_name
from ..types import PeftModelConfig
from ..utils import get_pip_config_args, get_real_path
from .cache_tracker import CacheTrackerActor
from .event import Event, EventCollectorActor, EventType
from .metrics import launch_metrics_export_server, record_metrics
from .resource import gather_node_info
from .status_guard import StatusGuardActor
from .utils import (
log_async,
log_sync,
merge_virtual_env_packages,
parse_replica_model_uid,
purge_dir,
)
from .virtual_env_manager import VirtualEnvManager as XinferenceVirtualEnvManager
try:
from xoscar.virtualenv import VirtualEnvManager
except ImportError:
VirtualEnvManager = None
if TYPE_CHECKING:
from .progress_tracker import Progressor
logger = getLogger(__name__)
MODEL_ACTOR_AUTO_RECOVER_LIMIT: Optional[int]
_MODEL_ACTOR_AUTO_RECOVER_LIMIT = os.getenv("XINFERENCE_MODEL_ACTOR_AUTO_RECOVER_LIMIT")
if _MODEL_ACTOR_AUTO_RECOVER_LIMIT is not None:
MODEL_ACTOR_AUTO_RECOVER_LIMIT = int(_MODEL_ACTOR_AUTO_RECOVER_LIMIT)
else:
MODEL_ACTOR_AUTO_RECOVER_LIMIT = None
@dataclass
class ModelStatus:
last_error: str = ""
@dataclass
class LaunchInfo:
cancel_event: threading.Event = field(default_factory=threading.Event)
# virtualenv manager
virtual_env_manager: Optional["VirtualEnvManager"] = None
# downloader, report progress or cancel entire download
downloader: Optional[CancellableDownloader] = None
# sub pools created for the model
sub_pools: Optional[List[str]] = None
class WorkerActor(xo.StatelessActor):
def __init__(
self,
supervisor_address: str,
main_pool: MainActorPoolType,
gpu_devices: List[int],
metrics_exporter_host: Optional[str] = None,
metrics_exporter_port: Optional[int] = None,
):
super().__init__()
# static attrs.
self._total_gpu_devices = gpu_devices
self._supervisor_address = supervisor_address
self._supervisor_ref: Optional[xo.ActorRefType] = None
self._main_pool = main_pool
self._main_pool.recover_sub_pool = self.recover_sub_pool
self._status_guard_ref: xo.ActorRefType[
"StatusGuardActor"
] = None # type: ignore
self._event_collector_ref: xo.ActorRefType[ # type: ignore
EventCollectorActor
] = None
self._cache_tracker_ref: xo.ActorRefType[
CacheTrackerActor
] = None # type: ignore
# Virtual environment management
self._virtual_env_manager: XinferenceVirtualEnvManager = None # type: ignore
# internal states.
# temporary placeholder during model launch process:
self._model_uid_launching_guard: Dict[str, LaunchInfo] = {}
# attributes maintained after model launched:
self._model_uid_to_model: Dict[str, xo.ActorRefType["ModelActor"]] = {}
self._model_uid_to_model_spec: Dict[str, Dict[str, Any]] = {}
self._model_uid_to_model_status: Dict[str, ModelStatus] = {}
self._gpu_to_model_uids: Dict[int, Set[str]] = defaultdict(set)
# Dict structure: gpu_index: {(replica_model_uid, model_type)}
self._user_specified_gpu_to_model_uids: Dict[int, Set[Tuple[str, str]]] = (
defaultdict(set)
)
self._allow_multi_replica_per_gpu = XINFERENCE_ALLOW_MULTI_REPLICA_PER_GPU
self._model_uid_to_addr: Dict[str, str] = {}
self._model_uid_to_recover_count: Dict[str, Optional[int]] = {}
self._model_uid_to_launch_args: Dict[str, Dict] = {}
if XINFERENCE_DISABLE_METRICS:
logger.info(
"Worker metrics is disabled due to the environment XINFERENCE_DISABLE_METRICS=1"
)
elif metrics_exporter_host is not None or metrics_exporter_port is not None:
# metrics export server.
logger.info(
f"Starting metrics export server at {metrics_exporter_host}:{metrics_exporter_port}" # noqa: E231
)
q: queue.Queue = queue.Queue()
self._metrics_thread = threading.Thread(
name="Metrics Export Server",
target=launch_metrics_export_server,
args=(q, metrics_exporter_host, metrics_exporter_port),
daemon=True,
)
self._metrics_thread.start()
logger.info("Checking metrics export server...")
while self._metrics_thread.is_alive():
try:
host, port = q.get(block=False)[:2]
logger.info(
f"Metrics server is started at: http://{host}:{port}" # noqa: E231
)
break
except queue.Empty:
pass
else:
raise Exception("Metrics server thread exit.")
# Initialize virtual environment manager
self._virtual_env_manager = XinferenceVirtualEnvManager(self.address)
self._lock = asyncio.Lock()
async def _reset_supervisor_refs(self):
async with self._lock:
self._supervisor_ref = None
self._status_guard_ref = None
self._event_collector_ref = None
self._cache_tracker_ref = None
self._progress_tracker_ref = None
async def recover_sub_pool(self, address):
logger.warning("Process %s is down.", address)
# Xoscar does not remove the address from sub_processes.
try:
await self._main_pool.remove_sub_pool(address)
except Exception:
pass
for model_uid, addr in self._model_uid_to_addr.items():
if addr == address:
launch_args = self._model_uid_to_launch_args.get(model_uid)
if launch_args is None:
logger.warning(
"Not recreate model because the it is down during launch."
)
else:
recover_count = self._model_uid_to_recover_count.get(model_uid)
try:
await self.terminate_model(model_uid, is_model_die=True)
except Exception:
pass
if recover_count is not None:
if recover_count > 0:
logger.warning(
"Recreating model actor %s, remain %s times ...",
model_uid,
recover_count - 1,
)
event_model_uid, _ = parse_replica_model_uid(model_uid)
try:
if self._event_collector_ref is not None:
await self._event_collector_ref.report_event(
event_model_uid,
Event(
event_type=EventType.WARNING,
event_ts=int(time.time()),
event_content="Recreate model",
),
)
except Exception as e:
# Report callback error can be log and ignore, should not interrupt the Process
logger.error("report_event error: %s" % (e))
finally:
del event_model_uid
self._model_uid_to_recover_count[model_uid] = (
recover_count - 1
)
await self.recover_model(launch_args)
else:
logger.warning("Stop recreating model actor.")
else:
logger.warning("Recreating model actor %s ...", model_uid)
await self.recover_model(launch_args)
break
@classmethod
def default_uid(cls) -> str:
return "worker"
def _get_spec_dicts_with_cache_status(
self, model_family: Any, cache_manager_cls: Type
) -> Tuple[List[dict], List[str]]:
"""
Build model_specs with cache_status and collect download_hubs.
"""
specs: List[dict] = []
download_hubs: List[str] = []
for spec in model_family.model_specs:
model_hub = spec.model_hub
if model_hub not in download_hubs:
download_hubs.append(model_hub)
family_copy = model_family.copy()
family_copy.model_specs = [spec]
cache_manager = cache_manager_cls(family_copy)
specs.append(
{**spec.dict(), "cache_status": cache_manager.get_cache_status()}
)
return specs, download_hubs
def _prefer_model_hub(self, model_family: Any, preferred_hub: str = "huggingface"):
"""
Return a copy of model_family with a single spec, preferring the given hub.
"""
specs = getattr(model_family, "model_specs", None)
if not specs:
return model_family
target_spec = next(
(
spec
for spec in specs
if getattr(spec, "model_hub", None) == preferred_hub
),
specs[0],
)
family_copy = model_family.copy()
family_copy.model_specs = [target_spec]
return family_copy
async def __post_create__(self):
from ..model.audio import (
CustomAudioModelFamilyV2,
generate_audio_description,
register_audio,
unregister_audio,
)
from ..model.embedding import (
CustomEmbeddingModelFamilyV2,
generate_embedding_description,
register_embedding,
unregister_embedding,
)
from ..model.flexible import (
FlexibleModelSpec,
generate_flexible_model_description,
register_flexible_model,
unregister_flexible_model,
)
from ..model.image import (
CustomImageModelFamilyV2,
generate_image_description,
register_image,
unregister_image,
)
from ..model.llm import (
CustomLLMFamilyV2,
generate_llm_version_info,
register_llm,
unregister_llm,
)
from ..model.rerank import (
CustomRerankModelFamilyV2,
generate_rerank_description,
register_rerank,
unregister_rerank,
)
from ..model.video import (
CustomVideoModelFamilyV2,
generate_video_description,
register_video,
unregister_video,
)
self._custom_register_type_to_cls: Dict[str, Tuple] = { # type: ignore
"LLM": (
CustomLLMFamilyV2,
register_llm,
unregister_llm,
generate_llm_version_info,
),
"embedding": (
CustomEmbeddingModelFamilyV2,
register_embedding,
unregister_embedding,
generate_embedding_description,
),
"rerank": (
CustomRerankModelFamilyV2,
register_rerank,
unregister_rerank,
generate_rerank_description,
),
"image": (
CustomImageModelFamilyV2,
register_image,
unregister_image,
generate_image_description,
),
"audio": (
CustomAudioModelFamilyV2,
register_audio,
unregister_audio,
generate_audio_description,
),
"flexible": (
FlexibleModelSpec,
register_flexible_model,
unregister_flexible_model,
generate_flexible_model_description,
),
"video": (
CustomVideoModelFamilyV2,
register_video,
unregister_video,
generate_video_description,
),
}
logger.info("Purge cache directory: %s", XINFERENCE_CACHE_DIR)
purge_dir(XINFERENCE_CACHE_DIR)
try:
await self.get_supervisor_ref(add_worker=True)
except Exception:
# Do not crash the worker if supervisor is down, auto re-connect later
logger.error(f"cannot connect to supervisor", exc_info=True)
if not XINFERENCE_DISABLE_HEALTH_CHECK:
from ..isolation import Isolation
# Run _periodical_report_status() in a dedicated thread.
self._isolation = Isolation(asyncio.new_event_loop(), threaded=True)
self._isolation.start()
asyncio.run_coroutine_threadsafe(
self._periodical_report_status(), loop=self._isolation.loop
)
logger.info(f"Xinference worker {self.address} started")
# Windows does not have signal handler
if os.name != "nt":
async def signal_handler():
try:
supervisor_ref = await self.get_supervisor_ref(add_worker=False)
await supervisor_ref.remove_worker(self.address)
except Exception as e:
# Ignore the error of rpc, anyway we are exiting
logger.exception("remove worker rpc error: %s", e)
os._exit(0)
loop = asyncio.get_running_loop()
loop.add_signal_handler(
signal.SIGINT, lambda: asyncio.create_task(signal_handler())
)
async def __pre_destroy__(self):
self._isolation.stop()
async def trigger_exit(self) -> bool:
try:
os.kill(os.getpid(), signal.SIGINT)
except Exception as e:
logger.info(f"trigger exit error: {e}")
return False
return True
async def get_supervisor_ref(self, add_worker: bool = True) -> xo.ActorRefType:
"""
Try connect to supervisor and return ActorRef. Raise exception on error
Params:
add_worker: By default will call supervisor.add_worker after first connect
"""
from .supervisor import SupervisorActor
async with self._lock:
if self._supervisor_ref is not None:
return self._supervisor_ref
supervisor_ref = await xo.actor_ref( # type: ignore
address=self._supervisor_address, uid=SupervisorActor.default_uid()
)
# Prevent concurrent operations leads to double initialization, check again.
if self._supervisor_ref is not None:
return self._supervisor_ref
self._supervisor_ref = supervisor_ref
if add_worker:
await self._supervisor_ref.ensure_worker(self.address)
if len(self._model_uid_to_model) == 0:
logger.info("Connected to supervisor as a fresh worker")
else:
try:
models = await self.list_models()
await self._supervisor_ref.restore_worker_models(
self.address, models
)
except Exception:
logger.exception(
"Failed to restore worker models to supervisor"
)
self._status_guard_ref = await xo.actor_ref(
address=self._supervisor_address, uid=StatusGuardActor.default_uid()
)
self._event_collector_ref = await xo.actor_ref(
address=self._supervisor_address, uid=EventCollectorActor.default_uid()
)
self._cache_tracker_ref = await xo.actor_ref(
address=self._supervisor_address, uid=CacheTrackerActor.default_uid()
)
self._progress_tracker_ref = None
# cache_tracker is on supervisor
from ..model.audio import get_audio_model_descriptions
from ..model.embedding import get_embedding_model_descriptions
from ..model.flexible import get_flexible_model_descriptions
from ..model.image import get_image_model_descriptions
from ..model.llm import get_llm_version_infos
from ..model.rerank import get_rerank_model_descriptions
from ..model.video import get_video_model_descriptions
# record model version
model_version_infos: Dict[str, List[Dict]] = {} # type: ignore
model_version_infos.update(get_llm_version_infos())
model_version_infos.update(get_embedding_model_descriptions())
model_version_infos.update(get_rerank_model_descriptions())
model_version_infos.update(get_image_model_descriptions())
model_version_infos.update(get_audio_model_descriptions())
model_version_infos.update(get_video_model_descriptions())
model_version_infos.update(get_flexible_model_descriptions())
await self._cache_tracker_ref.record_model_version(
model_version_infos, self.address
)
return self._supervisor_ref
@staticmethod
def get_devices_count():
from ..device_utils import gpu_count
return gpu_count()
@log_sync(logger=logger)
def get_model_count(self) -> int:
return len(self._model_uid_to_model)
async def is_model_vllm_backend(self, model_uid: str) -> bool:
_model_uid, _ = parse_replica_model_uid(model_uid)
supervisor_ref = await self.get_supervisor_ref()
model_ref = await supervisor_ref.get_model(_model_uid)
return await model_ref.is_vllm_backend()
def allocate_devices(self, model_uid: str, n_gpu: int) -> List[int]:
if n_gpu > len(self._total_gpu_devices):
raise RuntimeError("Requested GPUs exceed the number of available devices")
# If multi-replica-per-GPU is disabled, only pick currently idle GPUs.
if not self._allow_multi_replica_per_gpu:
occupied_devices: Set[int] = set()
for dev, model_uids in self._gpu_to_model_uids.items():
if model_uids:
occupied_devices.add(dev)
for dev, model_infos in self._user_specified_gpu_to_model_uids.items():
if model_infos:
occupied_devices.add(dev)
available_devices = [
dev for dev in self._total_gpu_devices if dev not in occupied_devices
]
if n_gpu > len(available_devices):
raise RuntimeError("No available slot found for the model")
selected_devices = available_devices[:n_gpu]
for dev in selected_devices:
self._gpu_to_model_uids[int(dev)].add(model_uid)
return sorted(selected_devices)
# Default: allow multi-tenant GPUs, pick least-loaded devices.
gpu_loads: List[Tuple[int, int, int]] = []
for dev in self._total_gpu_devices:
running_models = len(self._gpu_to_model_uids.get(dev, set()))
load = running_models + len(
self._user_specified_gpu_to_model_uids.get(dev, set())
)
# Prefer devices with fewer existing model processes when loads tie
gpu_loads.append((load, running_models, dev))
devices: List[int] = []
for _ in range(n_gpu):
gpu_loads.sort(key=lambda x: (x[0], x[1], x[2]))
load, running_models, dev = gpu_loads[0]
devices.append(dev)
gpu_loads[0] = (load + 1, running_models + 1, dev)
for dev in devices:
self._gpu_to_model_uids[int(dev)].add(model_uid)
return sorted(devices)
async def allocate_devices_with_gpu_idx(
self, model_uid: str, model_type: str, gpu_idx: List[int]
) -> List[int]:
"""
When user specifies the gpu_idx, allocate models on user-specified GPUs whenever possible
"""
# must be subset of total devices visible to this worker
if not set(gpu_idx) <= set(self._total_gpu_devices):
raise ValueError(
f"Worker {self.address} cannot use the GPUs with these indexes: {gpu_idx}. "
f"Worker {self.address} can only see these GPUs: {self._total_gpu_devices}."
)
# currently just report a warning log when there are already models on these GPUs
for idx in gpu_idx:
existing_model_uids = []
if idx in self._gpu_to_model_uids:
for rep_uid in self._gpu_to_model_uids[idx]:
existing_model_uids.append(rep_uid)
if not self._allow_multi_replica_per_gpu and (
existing_model_uids
or len(self._user_specified_gpu_to_model_uids.get(idx, set())) > 0
):
raise RuntimeError(
f"GPU index {idx} has been occupied with models: {existing_model_uids}, "
f"and multi-replica-per-GPU is disabled."
)
if existing_model_uids:
logger.warning(
f"WARNING!!! GPU index {idx} has been occupied "
f"with these models on it: {existing_model_uids}"
)
for idx in gpu_idx:
self._user_specified_gpu_to_model_uids[idx].add((model_uid, model_type))
return sorted(gpu_idx)
@log_async(logger=logger)
async def get_gpu_allocation_status(self) -> Dict[str, Any]:
"""Return current device allocation snapshot for scheduling/diagnostics."""
return {
"total": list(self._total_gpu_devices),
"models": {int(k): list(v) for k, v in self._gpu_to_model_uids.items()},
"user_specified": {
int(k): [list(t) for t in v]
for k, v in self._user_specified_gpu_to_model_uids.items()
},
"allow_multi_replica_per_gpu": self._allow_multi_replica_per_gpu,
}
def release_devices(self, model_uid: str):
for dev, model_uids in list(self._gpu_to_model_uids.items()):
if model_uid in model_uids:
model_uids.remove(model_uid)
if not model_uids:
del self._gpu_to_model_uids[dev]
# check user-specified slots
for dev in self._user_specified_gpu_to_model_uids:
model_infos = list(
filter(
lambda x: x[0] == model_uid,
self._user_specified_gpu_to_model_uids[dev],
)
)
for model_info in model_infos:
self._user_specified_gpu_to_model_uids[dev].remove(model_info)
async def _create_subpool(
self,
model_uid: str,
model_type: Optional[str] = None,
n_gpu: Optional[Union[int, str]] = "auto",
gpu_idx: Optional[List[int]] = None,
env: Optional[Dict[str, str]] = None,
start_python: Optional[str] = None,
) -> Tuple[str, List[str]]:
env = {} if env is None else env
devices = []
env_name = get_available_device_env_name() or "CUDA_VISIBLE_DEVICES"
if gpu_idx is None:
if isinstance(n_gpu, int) or (n_gpu == "auto" and gpu_count() > 0):
# Currently, n_gpu=auto means using 1 GPU
gpu_cnt = n_gpu if isinstance(n_gpu, int) else 1
devices = self.allocate_devices(model_uid=model_uid, n_gpu=gpu_cnt)
env[env_name] = ",".join([str(dev) for dev in devices])
logger.debug(f"GPU selected: {devices} for model {model_uid}")
if n_gpu is None:
env[env_name] = "-1"
logger.debug(f"GPU disabled for model {model_uid}")
else:
assert isinstance(gpu_idx, list)
devices = await self.allocate_devices_with_gpu_idx(
model_uid, model_type, gpu_idx # type: ignore
)
env[env_name] = ",".join([str(dev) for dev in devices])
subpool_address = await self._main_pool.append_sub_pool(
env=env, start_python=start_python
)
return subpool_address, [str(dev) for dev in devices]
def _check_model_is_valid(self, model_name: str, model_format: Optional[str]):
# baichuan-base and baichuan-chat depend on `cpm_kernels` module,
# but `cpm_kernels` cannot run on Darwin system.
if platform.system() == "Darwin" and model_format == "pytorch":
if "baichuan" in model_name:
raise ValueError(f"{model_name} model can't run on Darwin system.")
@log_sync(logger=logger)
async def register_model(self, model_type: str, model: str, persist: bool):
# TODO: centralized model registrations
if model_type in self._custom_register_type_to_cls:
(
model_spec_cls,
register_fn,
unregister_fn,
generate_fn,
) = self._custom_register_type_to_cls[model_type]
model_spec = model_spec_cls.parse_raw(model)
try:
register_fn(model_spec, persist)
await self._cache_tracker_ref.record_model_version(
generate_fn(model_spec), self.address
)
except ValueError as e:
raise e
except Exception as e:
unregister_fn(model_spec.model_name, raise_error=False)
raise e
else:
raise ValueError(f"Unsupported model type: {model_type}")
@log_sync(logger=logger)
async def unregister_model(self, model_type: str, model_name: str):
# TODO: centralized model registrations
if model_type in self._custom_register_type_to_cls:
_, _, unregister_fn, _ = self._custom_register_type_to_cls[model_type]
unregister_fn(model_name, False)
else:
raise ValueError(f"Unsupported model type: {model_type}")
@log_async(logger=logger)
async def update_model_type(self, model_type: str):
"""
Update model configurations for a specific model type by downloading
the latest JSON from the remote API and storing it locally.
Args:
model_type: Type of model (LLM, embedding, image, etc.)
"""
import json
import requests
supported_types = list(self._custom_register_type_to_cls.keys())
normalized_for_validation = model_type
if model_type.lower() == "llm" and "LLM" in supported_types:
normalized_for_validation = "LLM"
elif model_type.lower() == "llm" and "llm" in supported_types:
normalized_for_validation = "llm"
if normalized_for_validation not in supported_types:
logger.error(f"Unsupported model type: {normalized_for_validation}")
raise ValueError(
f"Unsupported model type '{model_type}'. "
f"Supported types are: {', '.join(supported_types)}"
)
# Construct the URL to download JSON
url = f"https://model.xinference.io/api/models/download?model_type={model_type.lower()}"
try:
# Download JSON from remote API
response = requests.get(url, timeout=30)
response.raise_for_status()
# Parse JSON response
model_data = response.json()
# Store the JSON data using CacheManager as built-in models
await self._store_complete_model_configurations(model_type, model_data)
# Dynamically reload built-in models to make them immediately available
try:
if model_type.lower() == "llm":
from ..model.llm import register_builtin_model
register_builtin_model()
elif model_type.lower() == "embedding":
from ..model.embedding import register_builtin_model
register_builtin_model()
elif model_type.lower() == "audio":
from ..model.audio import register_builtin_model
register_builtin_model()
elif model_type.lower() == "image":
from ..model.image import register_builtin_model
register_builtin_model()
elif model_type.lower() == "rerank":
from ..model.rerank import register_builtin_model
register_builtin_model()
elif model_type.lower() == "video":
from ..model.video import register_builtin_model
register_builtin_model()
else:
logger.warning(
f"No dynamic loading available for model type: {model_type}"
)
except Exception as reload_error:
logger.error(
f"Error reloading built-in models: {reload_error}",
exc_info=True,
)
# Don't fail the update if reload fails, just log the error
except requests.exceptions.RequestException as e:
logger.error(f"Network error downloading model configurations: {e}")
raise ValueError(f"Failed to download model configurations: {str(e)}")
except json.JSONDecodeError as e:
logger.error(f"JSON decode error: {e}")
raise ValueError(f"Invalid JSON response from remote API: {str(e)}")
except Exception as e:
logger.error(
f"Unexpected error during model update: {e}",
exc_info=True,
)
raise ValueError(f"Failed to update model configurations: {str(e)}")
async def _store_complete_model_configurations(self, model_type: str, model_data):
"""
Store complete model configurations as a unified JSON file.
This is used by update_model_type to preserve the original JSON structure.
Args:
model_type: Type of model (as provided by user, e.g., "llm")
model_data: JSON data containing model configurations (complete array)
"""
import json
from ..constants import XINFERENCE_MODEL_DIR
try:
model_type_lower = model_type.lower()
# Use the unified JSON file path (same as original update_model_type logic)
builtin_dir = os.path.join(
XINFERENCE_MODEL_DIR, "v2", "builtin", model_type_lower
)
json_file_path = os.path.join(
builtin_dir, f"{model_type_lower}_models.json"
)
# Ensure directory exists
os.makedirs(builtin_dir, exist_ok=True)
# Store the complete JSON file (preserving original structure)
with open(json_file_path, "w", encoding="utf-8") as f:
json.dump(model_data, f, indent=2, ensure_ascii=False)
except Exception as e:
logger.error(
f"Error storing complete model configurations: {str(e)}",
exc_info=True,
)
raise ValueError(f"Failed to store complete model configurations: {str(e)}")
@log_async(logger=logger)
async def list_model_registrations(
self, model_type: str, detailed: bool = False
) -> List[Dict[str, Any]]:
def sort_helper(item):
assert isinstance(item["model_name"], str)
return item.get("model_name").lower()
ret = []
if model_type == "LLM":
from ..model.llm import BUILTIN_LLM_FAMILIES, get_user_defined_llm_families
from ..model.llm.cache_manager import LLMCacheManager
# Add built-in LLM families
for family in BUILTIN_LLM_FAMILIES:
if detailed:
specs, download_hubs = self._get_spec_dicts_with_cache_status(
family, LLMCacheManager
)
ret.append(
{
**family.dict(),
"model_specs": specs,
"is_builtin": True,
"download_hubs": download_hubs,
}
)
else:
ret.append({"model_name": family.model_name, "is_builtin": True})
# Add user-defined LLM families
for family in get_user_defined_llm_families():
if detailed:
specs, download_hubs = self._get_spec_dicts_with_cache_status(
family, LLMCacheManager
)
ret.append(
{
**family.dict(),
"model_specs": specs,
"is_builtin": False,
"download_hubs": download_hubs,
}
)
else:
ret.append({"model_name": family.model_name, "is_builtin": False})
ret.sort(key=sort_helper)
return ret
elif model_type == "embedding":
from ..model.embedding import BUILTIN_EMBEDDING_MODELS
from ..model.embedding.cache_manager import EmbeddingCacheManager
from ..model.embedding.custom import get_user_defined_embeddings
# Add built-in embedding models
for model_name, family_list in BUILTIN_EMBEDDING_MODELS.items():
for family in family_list:
if detailed:
specs, download_hubs = self._get_spec_dicts_with_cache_status(
family, EmbeddingCacheManager
)
ret.append(
{
**family.dict(),
"model_specs": specs,
"is_builtin": True,
"download_hubs": download_hubs,
}
)
else:
ret.append({"model_name": model_name, "is_builtin": True})
# Add user-defined embedding models
for model_spec in get_user_defined_embeddings():
if detailed:
specs, download_hubs = self._get_spec_dicts_with_cache_status(
model_spec, EmbeddingCacheManager
)
ret.append(
{
**model_spec.dict(),
"model_specs": specs,
"is_builtin": False,
"download_hubs": download_hubs,
}
)
else:
ret.append(
{"model_name": model_spec.model_name, "is_builtin": False}
)
ret.sort(key=sort_helper)
return ret
elif model_type == "image":
from ..model.image import BUILTIN_IMAGE_MODELS
from ..model.image.cache_manager import ImageCacheManager
from ..model.image.custom import get_user_defined_images
# Add built-in image models (BUILTIN_IMAGE_MODELS contains model_name -> families list)
for model_name, families in BUILTIN_IMAGE_MODELS.items():
for family in families:
if detailed:
cache_manager = ImageCacheManager(family)
model_specs = [
{
"model_format": "pytorch",
"model_hub": family.model_hub,
"model_id": family.model_id,
"cache_status": cache_manager.get_cache_status(),
}
]
ret.append(
{
**family.dict(),
"model_specs": model_specs,
"is_builtin": True,
"download_hubs": [family.model_hub],
}
)
else:
ret.append({"model_name": model_name, "is_builtin": True})
# Add user-defined image models
for model_spec in get_user_defined_images():
if detailed:
cache_manager = ImageCacheManager(model_spec)
model_specs = [
{
"model_format": "pytorch",
"model_hub": model_spec.model_hub,
"model_id": model_spec.model_id,
"cache_status": cache_manager.get_cache_status(),
}
]
ret.append(
{
**model_spec.dict(),
"model_specs": model_specs,
"is_builtin": False,
"download_hubs": [model_spec.model_hub],
}
)
else:
ret.append(
{"model_name": model_spec.model_name, "is_builtin": False}
)
ret.sort(key=sort_helper)
return ret
elif model_type == "audio":
from ..model.audio import BUILTIN_AUDIO_MODELS
from ..model.audio.custom import get_user_defined_audios
from ..model.cache_manager import CacheManager
# Add built-in audio models (BUILTIN_AUDIO_MODELS contains model_name -> families list)
for model_name, families in BUILTIN_AUDIO_MODELS.items():
for family in families:
if detailed:
audio_cache_manager = CacheManager(family)
model_specs = [