forked from sgl-project/sglang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon.py
More file actions
3868 lines (3099 loc) · 123 KB
/
Copy pathcommon.py
File metadata and controls
3868 lines (3099 loc) · 123 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 2023-2024 SGLang Team
# 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.
# ==============================================================================
"""Common utilities."""
from __future__ import annotations
import argparse
import asyncio
import builtins
import ctypes
import functools
import importlib
import inspect
import io
import itertools
import json
import logging
import math
import os
import pickle
import platform
import random
import re
import resource
import shutil
import signal
import subprocess
import sys
import tempfile
import threading
import time
import traceback
import types
import uuid
import warnings
from collections import OrderedDict, defaultdict
from contextlib import contextmanager
from dataclasses import dataclass
from decimal import Decimal
from functools import lru_cache, partial
from importlib.metadata import PackageNotFoundError, version
from importlib.util import find_spec
from io import BytesIO
from json import JSONDecodeError
from multiprocessing.reduction import ForkingPickler
from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generic,
List,
Optional,
Protocol,
Sequence,
Tuple,
TypeVar,
Union,
)
from unittest import SkipTest
from urllib.parse import unquote, urlparse
import numpy as np
import orjson
import psutil
import pybase64
import requests
import torch
import torch.distributed as dist
import triton
from packaging import version as pkg_version
from PIL import Image
from starlette.routing import Mount
from torch import nn
from torch.library import Library
from torch.utils._contextlib import _DecoratorContextManager
from typing_extensions import Literal
from sglang.srt.environ import envs
from sglang.srt.observability.func_timer import enable_func_timer
from sglang.srt.utils.video_decoder import _BACKEND, VideoDecoderWrapper
if TYPE_CHECKING:
from sglang.srt.server_args import ServerArgs
logger = logging.getLogger(__name__)
torch_release = pkg_version.parse(torch.__version__).release
# https://pytorch.org/docs/stable/notes/hip.html#checking-for-hip
@lru_cache(maxsize=1)
def is_hip() -> bool:
return torch.version.hip is not None
if is_hip():
HIP_FP8_E4M3_FNUZ_MAX = 224.0
FP8_E4M3_MAX = HIP_FP8_E4M3_FNUZ_MAX
else:
FP8_E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max
FP8_E4M3_MIN = -FP8_E4M3_MAX
builtins.FP8_E4M3_MAX = FP8_E4M3_MAX
builtins.FP8_E4M3_MIN = FP8_E4M3_MIN
# explicitly use pure text format, with a newline at the end
# this makes it impossible to see the animation in the progress bar
# but will avoid messing up with ray or multiprocessing, which wraps
# each line of output with some prefix.
BAR_FORMAT = "{desc}: {percentage:3.0f}% Completed | {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]"
@lru_cache(maxsize=1)
def is_cuda():
return torch.cuda.is_available() and torch.version.cuda
@lru_cache(maxsize=1)
def is_cuda_alike():
return is_cuda() or is_hip()
@lru_cache(maxsize=1)
def is_hpu() -> bool:
return hasattr(torch, "hpu") and torch.hpu.is_available()
@lru_cache(maxsize=1)
def is_xpu() -> bool:
return hasattr(torch, "xpu") and torch.xpu.is_available()
@lru_cache(maxsize=1)
def is_npu() -> bool:
if not hasattr(torch, "npu"):
return False
if not torch.npu.is_available():
raise RuntimeError(
"torch_npu detected, but NPU device is not available or visible."
)
return True
@lru_cache(maxsize=1)
def is_host_cpu_x86() -> bool:
machine = platform.machine().lower()
return (
machine in ("x86_64", "amd64", "i386", "i686")
and hasattr(torch, "cpu")
and torch.cpu.is_available()
)
def is_host_cpu_arm64() -> bool:
machine = platform.machine().lower()
return (
machine in ("aarch64", "arm64")
and hasattr(torch, "cpu")
and torch.cpu.is_available()
)
@lru_cache(maxsize=1)
def is_cpu() -> bool:
is_host_cpu_supported = is_host_cpu_x86() or is_host_cpu_arm64()
return os.getenv("SGLANG_USE_CPU_ENGINE", "0") == "1" and is_host_cpu_supported
@lru_cache(maxsize=1)
def is_musa() -> bool:
try:
import torchada # noqa: F401
except ImportError:
return False
return hasattr(torch.version, "musa") and torch.version.musa is not None
@lru_cache(maxsize=1)
def is_mps() -> bool:
return torch.backends.mps.is_available()
def is_float4_e2m1fn_x2(dtype) -> bool:
"""Check if dtype is float4_e2m1fn_x2 and CUDA is available."""
target_dtype = getattr(torch, "float4_e2m1fn_x2", None)
return is_cuda() and dtype == target_dtype
def get_cuda_version():
if torch.version.cuda:
return tuple(map(int, torch.version.cuda.split(".")))
return (0, 0)
@contextmanager
def device_context(device: torch.device):
if device.type == "cpu" and is_cpu():
with torch.device("cpu"):
yield
else:
module = torch.get_device_module(device)
if module is not None:
with module.device(device.index):
yield
else:
raise ValueError(f"Unknown device module: {device}")
def _check_cuda_device_version(
device_capability_majors: List[int], cuda_version: Tuple[int, int]
):
if not is_cuda():
return False
return (
torch.cuda.get_device_capability()[0] in device_capability_majors
and tuple(map(int, torch.version.cuda.split(".")[:2])) >= cuda_version
)
is_ampere_with_cuda_12_3 = lru_cache(maxsize=1)(
partial(
_check_cuda_device_version, device_capability_majors=[8], cuda_version=(12, 3)
)
)
is_hopper_with_cuda_12_3 = lru_cache(maxsize=1)(
partial(
_check_cuda_device_version, device_capability_majors=[9], cuda_version=(12, 3)
)
)
is_blackwell_supported = is_blackwell = lru_cache(maxsize=1)(
partial(
_check_cuda_device_version,
device_capability_majors=[10, 11, 12],
cuda_version=(12, 8),
)
)
is_sm120_supported = lru_cache(maxsize=1)(
partial(
_check_cuda_device_version, device_capability_majors=[12], cuda_version=(12, 8)
)
)
is_sm100_supported = lru_cache(maxsize=1)(
partial(
_check_cuda_device_version, device_capability_majors=[10], cuda_version=(12, 8)
)
)
is_sm90_supported = lru_cache(maxsize=1)(
partial(
_check_cuda_device_version, device_capability_majors=[9], cuda_version=(12, 3)
)
)
try:
import sgl_kernel # noqa: F401
is_intel_amx_backend_available = hasattr(
torch.ops.sgl_kernel, "convert_weight_packed"
)
except:
is_intel_amx_backend_available = False
try:
# move torch._C._cpu._is_amx_tile_supported() from cpu_has_amx_support
# to support torch compile
is_amx_tile_supported = torch._C._cpu._is_amx_tile_supported()
except:
is_amx_tile_supported = False
def cpu_has_amx_support():
return is_amx_tile_supported and is_intel_amx_backend_available
def use_intel_amx_backend(layer):
return getattr(layer, "use_intel_amx_backend", False)
def xpu_has_xmx_support():
# TODO: update with XPU capability query
if is_xpu():
# currently only PVC/LNL/BMG supports F64, so we only support these now
return torch.xpu.get_device_properties().has_fp64
return False
def use_intel_xpu_backend():
return get_bool_env_var("SGLANG_USE_SGL_XPU") and is_xpu()
@lru_cache(maxsize=1)
def is_flashinfer_available():
"""
Check whether flashinfer is available.
As of Oct. 6, 2024, it is only available on NVIDIA GPUs.
"""
if not get_bool_env_var("SGLANG_IS_FLASHINFER_AVAILABLE", default="true"):
return False
return importlib.util.find_spec("flashinfer") is not None and is_cuda()
def is_nvidia_cublas_version_ge_12_9():
"""
temporary fix for issue #11272 (cublas 12.9+)
"""
for pkg in ("nvidia-cublas", "nvidia-cublas-cu12"):
if check_pkg_version_at_least(pkg, "12.9"):
return True
return False
def random_uuid() -> str:
return str(uuid.uuid4().hex)
_warned_bool_env_var_keys = set()
def get_bool_env_var(name: str, default: str = "false") -> bool:
# FIXME: move your environment variable to sglang.srt.environ
value = os.getenv(name, default)
value = value.lower()
truthy_values = ("true", "1")
falsy_values = ("false", "0")
if (value not in truthy_values) and (value not in falsy_values):
# Warn once per env var key (not per value), otherwise different keys that share the
# same invalid value may suppress warnings incorrectly.
if name not in _warned_bool_env_var_keys:
logger.warning(
f"get_bool_env_var({name}) encountered unrecognized value={value} and will treat as false"
)
_warned_bool_env_var_keys.add(name)
return value in truthy_values
def get_int_env_var(name: str, default: int = 0) -> int:
# FIXME: move your environment variable to sglang.srt.environ
value = os.getenv(name)
if value is None or not value.strip():
return default
try:
return int(value)
except ValueError:
return default
def support_triton(backend: str) -> bool:
return backend not in ["torch_native", "intel_amx"]
_ENABLE_TORCH_INFERENCE_MODE = get_bool_env_var(
"SGLANG_ENABLE_TORCH_INFERENCE_MODE", "false"
)
class DynamicGradMode(_DecoratorContextManager):
"""
A combination of torch.no_grad and torch.inference_mode,
with their behavior controlled by an environment variable. Just refer to them.
"""
@staticmethod
def set_inference_mode(mode: bool):
if isinstance(mode, bool):
global _ENABLE_TORCH_INFERENCE_MODE
_ENABLE_TORCH_INFERENCE_MODE = mode
else:
logger.warning("mode is not a boolean object")
def __init__(self, mode=True):
if not torch._jit_internal.is_scripting():
super().__init__()
if _ENABLE_TORCH_INFERENCE_MODE:
self.mode = mode
else:
self.prev = False
def __new__(cls, mode_or_orig_func=True if _ENABLE_TORCH_INFERENCE_MODE else None):
if mode_or_orig_func is None or isinstance(mode_or_orig_func, bool):
return super().__new__(cls)
return cls()(mode_or_orig_func)
def __enter__(self) -> None:
if _ENABLE_TORCH_INFERENCE_MODE:
self._inference_mode_context = torch._C._InferenceMode(self.mode)
self._inference_mode_context.__enter__()
else:
self.prev = torch.is_grad_enabled()
torch.set_grad_enabled(False)
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
if _ENABLE_TORCH_INFERENCE_MODE:
self._inference_mode_context.__exit__(exc_type, exc_value, traceback)
else:
torch.set_grad_enabled(self.prev)
def clone(self) -> "DynamicGradMode":
r"""
Create a copy of this class
"""
if _ENABLE_TORCH_INFERENCE_MODE:
return self.__class__(self.mode)
else:
return self.__class__()
show_time_cost = False
time_infos = {}
def enable_show_time_cost():
global show_time_cost
show_time_cost = True
class TimeInfo:
def __init__(self, name, interval=0.1, color=0, indent=0):
self.name = name
self.interval = interval
self.color = color
self.indent = indent
self.acc_time = 0
self.last_acc_time = 0
def check(self):
if self.acc_time - self.last_acc_time > self.interval:
self.last_acc_time = self.acc_time
return True
return False
def pretty_print(self):
print(f"\x1b[{self.color}m", end="")
print("-" * self.indent * 2, end="")
print(f"{self.name}: {self.acc_time:.3f}s\x1b[0m")
def mark_start(name, interval=0.1, color=0, indent=0):
global time_infos, show_time_cost
if not show_time_cost:
return
torch.cuda.synchronize()
if time_infos.get(name, None) is None:
time_infos[name] = TimeInfo(name, interval, color, indent)
time_infos[name].acc_time -= time.perf_counter()
def mark_end(name):
global time_infos, show_time_cost
if not show_time_cost:
return
torch.cuda.synchronize()
time_infos[name].acc_time += time.perf_counter()
if time_infos[name].check():
time_infos[name].pretty_print()
def calculate_time(show=False, min_cost_ms=0.0):
def wrapper(func):
def inner_func(*args, **kwargs):
torch.cuda.synchronize()
if show:
start_time = time.perf_counter()
result = func(*args, **kwargs)
torch.cuda.synchronize()
if show:
cost_time = (time.perf_counter() - start_time) * 1000
if cost_time > min_cost_ms:
print(f"Function {func.__name__} took {cost_time} ms to run.")
return result
return inner_func
return wrapper
def get_available_gpu_memory(
device, gpu_id, distributed=False, empty_cache=True, cpu_group=None
):
"""
Get available memory for cuda:gpu_id device.
When distributed is True, the available memory is the minimum available memory of all GPUs.
"""
if device == "cuda":
num_gpus = torch.cuda.device_count()
assert gpu_id < num_gpus
if torch.cuda.current_device() != gpu_id:
print(
f"WARNING: current device is not {gpu_id}, but {torch.cuda.current_device()}, ",
"which may cause useless memory allocation for torch CUDA context.",
)
if empty_cache:
torch.cuda.empty_cache()
props = torch.cuda.get_device_properties(gpu_id)
if props.is_integrated:
# On these devices, which use sysmem as device mem, torch.cuda.mem_get_info()
# only reports "free" memory, which can be lower than what is actually
# available due to not including cache memory. So we use the system available
# memory metric instead.
free_gpu_memory = psutil.virtual_memory().available
else:
free_gpu_memory, _ = torch.cuda.mem_get_info(gpu_id)
elif device == "xpu":
num_gpus = torch.xpu.device_count()
assert gpu_id < num_gpus
if torch.xpu.current_device() != gpu_id:
print(
f"WARNING: current device is not {gpu_id}, but {torch.xpu.current_device()}, ",
"which may cause useless memory allocation for torch XPU context.",
)
if empty_cache:
torch.xpu.empty_cache()
used_memory = torch.xpu.memory_allocated()
total_gpu_memory = torch.xpu.get_device_properties(gpu_id).total_memory
free_gpu_memory = total_gpu_memory - used_memory
elif device == "hpu":
num_gpus = torch.hpu.device_count()
assert gpu_id < num_gpus
if torch.hpu.current_device() != gpu_id:
print(
f"WARNING: current device is not {gpu_id}, but {torch.hpu.current_device()}, ",
"which may cause useless memory allocation for torch HPU context.",
)
free_gpu_memory, total_gpu_memory = torch.hpu.mem_get_info()
elif device == "cpu":
# TODO: rename the variables in the current function to be not GPU specific
total_free_memory = psutil.virtual_memory().available
n_numa_node: int = len(get_cpu_ids_by_node())
free_gpu_memory = round(total_free_memory / n_numa_node, 3)
elif device == "npu":
num_gpus = torch.npu.device_count()
assert gpu_id < num_gpus
if torch.npu.current_device() != gpu_id:
print(
f"WARNING: current device is not {gpu_id}, but {torch.npu.current_device()}, ",
"which may cause useless memory allocation for torch NPU context.",
)
if empty_cache:
torch.npu.empty_cache()
free_gpu_memory, total_gpu_memory = torch.npu.mem_get_info()
elif device == "musa":
num_gpus = torch.musa.device_count()
assert gpu_id < num_gpus
if torch.musa.current_device() != gpu_id:
print(
f"WARNING: current device is not {gpu_id}, but {torch.musa.current_device()}, ",
"which may cause useless memory allocation for torch MUSA context.",
)
if empty_cache:
torch.musa.empty_cache()
props = torch.musa.get_device_properties(gpu_id)
if props.is_integrated:
# On these devices, which use sysmem as device mem, torch.musa.mem_get_info()
# only reports "free" memory, which can be lower than what is actually
# available due to not including cache memory. So we use the system available
# memory metric instead.
free_gpu_memory = psutil.virtual_memory().available
free_gpu_memory, total_gpu_memory = torch.musa.mem_get_info()
elif device == "mps":
free_gpu_memory = psutil.virtual_memory().available
if distributed:
tensor = torch.tensor(free_gpu_memory, dtype=torch.float32)
torch.distributed.all_reduce(
tensor, op=torch.distributed.ReduceOp.MIN, group=cpu_group
)
free_gpu_memory = tensor.item()
return free_gpu_memory / (1 << 30)
def is_pin_memory_available(device=None) -> bool:
if not torch.cuda.is_available():
return False
if device is not None and str(device) == "cpu":
return False
return True
class LayerFn(Protocol):
def __call__(self, idx: int, prefix: str) -> torch.nn.Module: ...
def make_layers(
num_hidden_layers: int,
layer_fn: LayerFn,
pp_rank: Optional[int] = None,
pp_size: Optional[int] = None,
prefix: str = "",
return_tuple: bool = False,
offloader_kwargs: Optional[Dict[str, Any]] = None,
) -> Tuple[torch.nn.Module, int, int]:
"""Make a list of layers with the given layer function"""
# circular imports
from sglang.srt.distributed import get_pp_indices
from sglang.srt.layers.utils import PPMissingLayer
from sglang.srt.utils.offloader import get_offloader
assert not pp_size or num_hidden_layers >= pp_size
start_layer, end_layer = (
get_pp_indices(
num_hidden_layers,
pp_rank,
pp_size,
)
if pp_rank is not None and pp_size is not None
else (0, num_hidden_layers)
)
modules = torch.nn.ModuleList(
[PPMissingLayer(return_tuple=return_tuple) for _ in range(start_layer)]
+ get_offloader().wrap_modules(
(
layer_fn(idx=idx, prefix=add_prefix(idx, prefix))
for idx in range(start_layer, end_layer)
),
**(offloader_kwargs or {}),
)
+ [
PPMissingLayer(return_tuple=return_tuple)
for _ in range(end_layer, num_hidden_layers)
]
)
if pp_rank is None or pp_size is None:
return modules
return modules, start_layer, end_layer
def make_layers_non_pp(
num_hidden_layers: int,
layer_fn: LayerFn,
prefix: str = "",
) -> torch.nn.ModuleList:
from sglang.srt.utils.offloader import get_offloader
layers = torch.nn.ModuleList(
get_offloader().wrap_modules(
(
layer_fn(idx=idx, prefix=add_prefix(idx, prefix))
for idx in range(num_hidden_layers)
)
)
)
return layers
@lru_cache(maxsize=1)
def get_device_module():
return torch.get_device_module()
def set_random_seed(seed: int) -> None:
"""Set the random seed for all libraries."""
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
def load_audio(
audio_file: str, sr: Optional[int] = None, mono: bool = True
) -> np.ndarray:
if sr is None:
sr = 16000
# Normalize input: resolve URL / base64 / file:// to bytes or path
if isinstance(audio_file, bytes):
source = audio_file
elif isinstance(audio_file, str) and audio_file.startswith("data:"):
source = pybase64.b64decode(audio_file.split(",")[1], validate=True)
elif isinstance(audio_file, str) and (
audio_file.startswith("http://") or audio_file.startswith("https://")
):
timeout = int(os.getenv("REQUEST_TIMEOUT", "5"))
with requests.get(audio_file, timeout=timeout) as response:
response.raise_for_status()
source = response.content
elif isinstance(audio_file, str) and audio_file.startswith("file://"):
source = unquote(urlparse(audio_file).path)
elif isinstance(audio_file, str):
source = audio_file
else:
raise ValueError(f"Invalid audio format: {audio_file}")
if _BACKEND == "torchcodec":
from torchcodec.decoders import AudioDecoder
decoder = AudioDecoder(
source,
sample_rate=sr,
num_channels=1 if mono else None,
)
samples = decoder.get_all_samples()
if mono:
return samples.data.squeeze(0).numpy()
return samples.data.T.numpy()
# Fallback: soundfile + torchaudio (ARM / no FFmpeg)
import soundfile as sf
import torch
import torchaudio
if isinstance(source, bytes):
audio, original_sr = sf.read(BytesIO(source))
else:
audio, original_sr = sf.read(source)
if mono and len(audio.shape) > 1:
audio = np.mean(audio, axis=1)
if original_sr != sr:
audio_tensor = torch.from_numpy(audio).float()
if audio_tensor.dim() == 1:
audio_tensor = audio_tensor.unsqueeze(0)
else:
audio_tensor = audio_tensor.T
audio_tensor = torchaudio.functional.resample(
audio_tensor, orig_freq=original_sr, new_freq=sr
)
if audio_tensor.shape[0] == 1:
audio = audio_tensor.squeeze(0).numpy()
else:
audio = audio_tensor.T.numpy()
return audio
@dataclass
class ImageData:
url: str
detail: Optional[Literal["auto", "low", "high"]] = "auto"
max_dynamic_patch: Optional[int] = None
def load_image(
image_file: Union[Image.Image, str, ImageData, bytes],
) -> tuple[Image.Image, tuple[int, int]]:
if isinstance(image_file, ImageData):
image_file = image_file.url
image = image_size = None
if isinstance(image_file, Image.Image):
image = image_file
image_size = (image.width, image.height)
elif isinstance(image_file, bytes):
image = Image.open(BytesIO(image_file))
elif image_file.startswith("http://") or image_file.startswith("https://"):
timeout = int(os.getenv("REQUEST_TIMEOUT", "3"))
response = requests.get(image_file, stream=True, timeout=timeout)
try:
response.raise_for_status()
image = Image.open(response.raw)
image.load() # Force loading to avoid issues after closing the stream
finally:
response.close()
elif image_file.startswith("file://"):
image_file = unquote(urlparse(image_file).path)
image = Image.open(image_file)
elif image_file.lower().endswith(("png", "jpg", "jpeg", "webp", "gif")):
image = Image.open(image_file)
elif image_file.startswith("data:"):
image_file = image_file.split(",")[1]
image = Image.open(BytesIO(pybase64.b64decode(image_file, validate=True)))
elif isinstance(image_file, str):
image = Image.open(BytesIO(pybase64.b64decode(image_file, validate=True)))
else:
raise ValueError(f"Invalid image: {image_file}")
return image, image_size
def get_image_bytes(image_file: Union[str, bytes]):
if isinstance(image_file, bytes):
return image_file
elif image_file.startswith("http://") or image_file.startswith("https://"):
timeout = int(os.getenv("REQUEST_TIMEOUT", "3"))
response = requests.get(image_file, timeout=timeout)
return response.content
elif image_file.startswith("file://"):
image_file = unquote(urlparse(image_file).path)
with open(image_file, "rb") as f:
return f.read()
elif image_file.lower().endswith(("png", "jpg", "jpeg", "webp", "gif")):
with open(image_file, "rb") as f:
return f.read()
elif image_file.startswith("data:"):
image_file = image_file.split(",")[1]
return pybase64.b64decode(image_file, validate=True)
elif isinstance(image_file, str):
return pybase64.b64decode(image_file, validate=True)
else:
raise NotImplementedError(f"Invalid image: {image_file}")
def _normalize_video_input(
video_file: Union[str, bytes],
) -> Union[str, bytes, None]:
"""Normalize video input (URL, base64, file://, etc.) to a file path or bytes.
Returns a file path or bytes suitable for a decoder, or None on failure.
URLs and base64 are returned as bytes (no temp files needed since both
torchcodec and VideoDecoderWrapper accept bytes natively).
"""
if isinstance(video_file, bytes):
return video_file
elif isinstance(video_file, str):
if video_file.startswith(("http://", "https://")):
timeout = int(os.getenv("REQUEST_TIMEOUT", "10"))
response = requests.get(video_file, stream=True, timeout=timeout)
response.raise_for_status()
return response.content
elif video_file.startswith("data:"):
_, encoded = video_file.split(",", 1)
return pybase64.b64decode(encoded, validate=True)
elif video_file.startswith("file://"):
return unquote(urlparse(video_file).path)
elif os.path.isfile(unquote(urlparse(video_file).path)):
return video_file
else:
return pybase64.b64decode(video_file, validate=True)
else:
return None
def load_video(video_file: Union[str, bytes], use_gpu: bool = True):
if isinstance(video_file, (list, tuple, torch.Tensor, np.ndarray)):
return video_file
source = _normalize_video_input(video_file)
if source is None:
raise ValueError(f"Unsupported video input type: {type(video_file)}")
device = "cuda" if use_gpu else "cpu"
return VideoDecoderWrapper(source, device=device)
def sample_video_frames(video, *, desired_fps: int, max_frames: int) -> list[int]:
total_frames = len(video)
assert total_frames > 0, "Video must have at least one frame"
avg_fps = video.avg_fps
duration = total_frames / avg_fps if avg_fps > 0 else 0
fps = min(desired_fps, avg_fps)
num_frames = math.floor(duration * fps)
num_frames = min(max_frames, num_frames, total_frames)
num_frames = max(1, num_frames) # At least one frame
if num_frames == total_frames:
return list(range(total_frames))
else:
return np.linspace(0, total_frames - 1, num_frames, dtype=int).tolist()
def encode_video(video_path, frame_count_limit=None):
if not os.path.exists(video_path):
logger.error(f"Video {video_path} does not exist")
return []
if frame_count_limit == 0:
return []
def uniform_sample(l, n):
gap = len(l) / n
idxs = [int(i * gap + gap / 2) for i in range(n)]
return [l[i] for i in idxs]
decoder = VideoDecoderWrapper(video_path)
avg_fps = decoder.avg_fps
total_frames = len(decoder)
sample_fps = round(avg_fps / 1)
if sample_fps == 0:
sample_fps = 1
frame_indices = [i for i in range(0, total_frames, sample_fps)]
if frame_count_limit is not None and len(frame_indices) > frame_count_limit:
frame_indices = uniform_sample(frame_indices, frame_count_limit)
if not frame_indices:
return []
frames_data = decoder.get_frames_at(frame_indices)
frames = [Image.fromarray(v.astype("uint8")) for v in frames_data]
return frames
def suppress_noisy_warnings():
"""Suppress known noisy warnings from third-party libraries."""
warnings.filterwarnings(
"ignore", category=UserWarning, message="The given NumPy array is not writable"
)
warnings.filterwarnings(
"ignore",
message="The cuda.cudart module is deprecated",
category=FutureWarning,
)
warnings.filterwarnings(
"ignore",
message="The cuda.nvrtc module is deprecated",
category=FutureWarning,
)
# Suppress noisy third-party HTTP loggers.
# huggingface_hub uses httpx which logs every HTTP request at INFO level.
for name in ("httpx", "httpcore"):
logging.getLogger(name).setLevel(logging.WARNING)
def suppress_other_loggers():
suppress_noisy_warnings()
try:
from vllm.logger import logger as vllm_default_logger
except ImportError:
return
vllm_default_logger.setLevel(logging.WARN)
logging.getLogger("vllm.distributed.device_communicators.pynccl").setLevel(
logging.WARN
)
logging.getLogger("vllm.distributed.device_communicators.shm_broadcast").setLevel(
logging.WARN
)
logging.getLogger("vllm.config").setLevel(logging.ERROR)
def assert_pkg_version(pkg: str, min_version: str, message: str):
try:
installed_version = version(pkg)
if pkg_version.parse(installed_version) < pkg_version.parse(min_version):
raise Exception(
f"{pkg} is installed with version {installed_version}, which "
f"is less than the minimum required version {min_version}. " + message
)
except PackageNotFoundError:
raise Exception(
f"{pkg} with minimum required version {min_version} is not installed. "
+ message
)
def check_pkg_version_at_least(pkg: str, min_version: str) -> bool:
"""
Check if a package is installed and meets the minimum version requirement.
Args:
pkg: Package name (distribution name, e.g., "flashinfer-python")
min_version: Minimum version required (e.g., "0.6.6")
Returns:
True if package is installed and version >= min_version, False otherwise
"""
try:
installed_version = version(pkg)
return pkg_version.parse(installed_version) >= pkg_version.parse(min_version)
except PackageNotFoundError:
return False
def kill_process_tree(parent_pid, include_parent: bool = True, skip_pid: int = None):
"""Kill the process and all its child processes."""
if parent_pid is None:
parent_pid = os.getpid()
include_parent = False
try:
itself = psutil.Process(parent_pid)
except psutil.NoSuchProcess:
return