ZTWHHH commited on
Commit
fea988d
·
verified ·
1 Parent(s): 936cdac

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/sqrt_cpu_dispatch.h +26 -0
  2. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/sum_compositeexplicitautograd_dispatch.h +25 -0
  3. vllm/lib/python3.10/site-packages/_pytest/__pycache__/__init__.cpython-310.pyc +0 -0
  4. vllm/lib/python3.10/site-packages/_pytest/__pycache__/_argcomplete.cpython-310.pyc +0 -0
  5. vllm/lib/python3.10/site-packages/_pytest/__pycache__/compat.cpython-310.pyc +0 -0
  6. vllm/lib/python3.10/site-packages/_pytest/__pycache__/debugging.cpython-310.pyc +0 -0
  7. vllm/lib/python3.10/site-packages/_pytest/__pycache__/faulthandler.cpython-310.pyc +0 -0
  8. vllm/lib/python3.10/site-packages/_pytest/__pycache__/freeze_support.cpython-310.pyc +0 -0
  9. vllm/lib/python3.10/site-packages/_pytest/__pycache__/legacypath.cpython-310.pyc +0 -0
  10. vllm/lib/python3.10/site-packages/_pytest/__pycache__/main.cpython-310.pyc +0 -0
  11. vllm/lib/python3.10/site-packages/_pytest/__pycache__/monkeypatch.cpython-310.pyc +0 -0
  12. vllm/lib/python3.10/site-packages/_pytest/__pycache__/nodes.cpython-310.pyc +0 -0
  13. vllm/lib/python3.10/site-packages/_pytest/__pycache__/pathlib.cpython-310.pyc +0 -0
  14. vllm/lib/python3.10/site-packages/_pytest/__pycache__/pytester_assertions.cpython-310.pyc +0 -0
  15. vllm/lib/python3.10/site-packages/_pytest/__pycache__/python.cpython-310.pyc +0 -0
  16. vllm/lib/python3.10/site-packages/_pytest/__pycache__/python_path.cpython-310.pyc +0 -0
  17. vllm/lib/python3.10/site-packages/_pytest/__pycache__/scope.cpython-310.pyc +0 -0
  18. vllm/lib/python3.10/site-packages/_pytest/__pycache__/skipping.cpython-310.pyc +0 -0
  19. vllm/lib/python3.10/site-packages/_pytest/__pycache__/stash.cpython-310.pyc +0 -0
  20. vllm/lib/python3.10/site-packages/_pytest/__pycache__/stepwise.cpython-310.pyc +0 -0
  21. vllm/lib/python3.10/site-packages/_pytest/__pycache__/threadexception.cpython-310.pyc +0 -0
  22. vllm/lib/python3.10/site-packages/_pytest/__pycache__/timing.cpython-310.pyc +0 -0
  23. vllm/lib/python3.10/site-packages/_pytest/__pycache__/unittest.cpython-310.pyc +0 -0
  24. vllm/lib/python3.10/site-packages/_pytest/__pycache__/unraisableexception.cpython-310.pyc +0 -0
  25. vllm/lib/python3.10/site-packages/gpustat/__init__.py +30 -0
  26. vllm/lib/python3.10/site-packages/gpustat/__main__.py +9 -0
  27. vllm/lib/python3.10/site-packages/gpustat/__pycache__/__main__.cpython-310.pyc +0 -0
  28. vllm/lib/python3.10/site-packages/gpustat/__pycache__/_shtab.cpython-310.pyc +0 -0
  29. vllm/lib/python3.10/site-packages/gpustat/__pycache__/_version.cpython-310.pyc +0 -0
  30. vllm/lib/python3.10/site-packages/gpustat/__pycache__/core.cpython-310.pyc +0 -0
  31. vllm/lib/python3.10/site-packages/gpustat/__pycache__/nvml.cpython-310.pyc +0 -0
  32. vllm/lib/python3.10/site-packages/gpustat/__pycache__/test_gpustat.cpython-310.pyc +0 -0
  33. vllm/lib/python3.10/site-packages/gpustat/__pycache__/util_test.cpython-310.pyc +0 -0
  34. vllm/lib/python3.10/site-packages/gpustat/_shtab.py +8 -0
  35. vllm/lib/python3.10/site-packages/gpustat/_version.py +21 -0
  36. vllm/lib/python3.10/site-packages/gpustat/cli.py +221 -0
  37. vllm/lib/python3.10/site-packages/gpustat/core.py +764 -0
  38. vllm/lib/python3.10/site-packages/gpustat/nvml.py +160 -0
  39. vllm/lib/python3.10/site-packages/gpustat/test_gpustat.py +703 -0
  40. vllm/lib/python3.10/site-packages/gpustat/util.py +103 -0
  41. vllm/lib/python3.10/site-packages/gpustat/util_test.py +29 -0
  42. vllm/lib/python3.10/site-packages/httptools-0.6.4.dist-info/INSTALLER +1 -0
  43. vllm/lib/python3.10/site-packages/httptools-0.6.4.dist-info/LICENSE +21 -0
  44. vllm/lib/python3.10/site-packages/httptools-0.6.4.dist-info/METADATA +133 -0
  45. vllm/lib/python3.10/site-packages/httptools-0.6.4.dist-info/RECORD +22 -0
  46. vllm/lib/python3.10/site-packages/httptools-0.6.4.dist-info/REQUESTED +0 -0
  47. vllm/lib/python3.10/site-packages/httptools-0.6.4.dist-info/WHEEL +8 -0
  48. vllm/lib/python3.10/site-packages/httptools-0.6.4.dist-info/top_level.txt +1 -0
  49. vllm/lib/python3.10/site-packages/inflection/__init__.py +426 -0
  50. vllm/lib/python3.10/site-packages/inflection/__pycache__/__init__.cpython-310.pyc +0 -0
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/sqrt_cpu_dispatch.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API at::Tensor sqrt(const at::Tensor & self);
21
+ TORCH_API at::Tensor & sqrt_out(at::Tensor & out, const at::Tensor & self);
22
+ TORCH_API at::Tensor & sqrt_outf(const at::Tensor & self, at::Tensor & out);
23
+ TORCH_API at::Tensor & sqrt_(at::Tensor & self);
24
+
25
+ } // namespace cpu
26
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/sum_compositeexplicitautograd_dispatch.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API at::Tensor sum(const at::Tensor & self, c10::optional<at::ScalarType> dtype=c10::nullopt);
21
+ TORCH_API at::Tensor & sum_out(at::Tensor & out, const at::Tensor & self, c10::optional<at::ScalarType> dtype=c10::nullopt);
22
+ TORCH_API at::Tensor & sum_outf(const at::Tensor & self, c10::optional<at::ScalarType> dtype, at::Tensor & out);
23
+
24
+ } // namespace compositeexplicitautograd
25
+ } // namespace at
vllm/lib/python3.10/site-packages/_pytest/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (407 Bytes). View file
 
vllm/lib/python3.10/site-packages/_pytest/__pycache__/_argcomplete.cpython-310.pyc ADDED
Binary file (4.1 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/__pycache__/compat.cpython-310.pyc ADDED
Binary file (9.38 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/__pycache__/debugging.cpython-310.pyc ADDED
Binary file (11.7 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/__pycache__/faulthandler.cpython-310.pyc ADDED
Binary file (2.87 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/__pycache__/freeze_support.cpython-310.pyc ADDED
Binary file (1.42 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/__pycache__/legacypath.cpython-310.pyc ADDED
Binary file (18 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/__pycache__/main.cpython-310.pyc ADDED
Binary file (27.6 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/__pycache__/monkeypatch.cpython-310.pyc ADDED
Binary file (12.6 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/__pycache__/nodes.cpython-310.pyc ADDED
Binary file (23.4 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/__pycache__/pathlib.cpython-310.pyc ADDED
Binary file (28.4 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/__pycache__/pytester_assertions.cpython-310.pyc ADDED
Binary file (1.8 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/__pycache__/python.cpython-310.pyc ADDED
Binary file (48.7 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/__pycache__/python_path.cpython-310.pyc ADDED
Binary file (1.12 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/__pycache__/scope.cpython-310.pyc ADDED
Binary file (3.15 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/__pycache__/skipping.cpython-310.pyc ADDED
Binary file (8.61 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/__pycache__/stash.cpython-310.pyc ADDED
Binary file (3.95 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/__pycache__/stepwise.cpython-310.pyc ADDED
Binary file (3.83 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/__pycache__/threadexception.cpython-310.pyc ADDED
Binary file (3.52 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/__pycache__/timing.cpython-310.pyc ADDED
Binary file (592 Bytes). View file
 
vllm/lib/python3.10/site-packages/_pytest/__pycache__/unittest.cpython-310.pyc ADDED
Binary file (12.8 kB). View file
 
vllm/lib/python3.10/site-packages/_pytest/__pycache__/unraisableexception.cpython-310.pyc ADDED
Binary file (3.52 kB). View file
 
vllm/lib/python3.10/site-packages/gpustat/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The gpustat module.
3
+ """
4
+
5
+ # isort: skip_file
6
+ try:
7
+ from ._version import version as __version__
8
+ from ._version import version_tuple as __version_tuple__
9
+ except (ImportError, AttributeError) as ex:
10
+ raise ImportError(
11
+ "Unable to find `gpustat.__version__` string. "
12
+ "Please try reinstalling gpustat; or if you are on a development "
13
+ "version, then run `pip install -e .` and try again."
14
+ ) from ex
15
+
16
+ from .core import GPUStat, GPUStatCollection
17
+ from .core import new_query, gpu_count, is_available
18
+ from .cli import print_gpustat, main
19
+
20
+
21
+ __all__ = (
22
+ '__version__',
23
+ 'GPUStat',
24
+ 'GPUStatCollection',
25
+ 'new_query',
26
+ 'gpu_count',
27
+ 'is_available',
28
+ 'print_gpustat',
29
+ 'main',
30
+ )
vllm/lib/python3.10/site-packages/gpustat/__main__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ gpustat.__main__ module (to support python -m gpustat)
3
+ """
4
+
5
+ from .cli import main
6
+
7
+
8
+ if __name__ == '__main__':
9
+ main()
vllm/lib/python3.10/site-packages/gpustat/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (306 Bytes). View file
 
vllm/lib/python3.10/site-packages/gpustat/__pycache__/_shtab.cpython-310.pyc ADDED
Binary file (381 Bytes). View file
 
vllm/lib/python3.10/site-packages/gpustat/__pycache__/_version.cpython-310.pyc ADDED
Binary file (533 Bytes). View file
 
vllm/lib/python3.10/site-packages/gpustat/__pycache__/core.cpython-310.pyc ADDED
Binary file (21.9 kB). View file
 
vllm/lib/python3.10/site-packages/gpustat/__pycache__/nvml.cpython-310.pyc ADDED
Binary file (4.11 kB). View file
 
vllm/lib/python3.10/site-packages/gpustat/__pycache__/test_gpustat.cpython-310.pyc ADDED
Binary file (21.1 kB). View file
 
vllm/lib/python3.10/site-packages/gpustat/__pycache__/util_test.cpython-310.pyc ADDED
Binary file (1 kB). View file
 
vllm/lib/python3.10/site-packages/gpustat/_shtab.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ FILE = None
2
+ DIRECTORY = DIR = None
3
+
4
+
5
+ def add_argument_to(parser, *args, **kwargs):
6
+ from argparse import Action
7
+ Action.complete = None
8
+ return parser
vllm/lib/python3.10/site-packages/gpustat/_version.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # file generated by setuptools-scm
2
+ # don't change, don't track in version control
3
+
4
+ __all__ = ["__version__", "__version_tuple__", "version", "version_tuple"]
5
+
6
+ TYPE_CHECKING = False
7
+ if TYPE_CHECKING:
8
+ from typing import Tuple
9
+ from typing import Union
10
+
11
+ VERSION_TUPLE = Tuple[Union[int, str], ...]
12
+ else:
13
+ VERSION_TUPLE = object
14
+
15
+ version: str
16
+ __version__: str
17
+ __version_tuple__: VERSION_TUPLE
18
+ version_tuple: VERSION_TUPLE
19
+
20
+ __version__ = version = '1.1.1'
21
+ __version_tuple__ = version_tuple = (1, 1, 1)
vllm/lib/python3.10/site-packages/gpustat/cli.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import time
4
+ from contextlib import suppress
5
+
6
+ from blessed import Terminal
7
+
8
+ from gpustat import __version__
9
+ from gpustat.core import GPUStatCollection
10
+
11
+
12
+ SHTAB_PREAMBLE = {
13
+ 'zsh': '''\
14
+ # % gpustat -i <TAB>
15
+ # float
16
+ # % gpustat -i -<TAB>
17
+ # option
18
+ # -a Display all gpu properties above
19
+ # ...
20
+ _complete_for_one_or_zero() {
21
+ if [[ ${words[CURRENT]} == -* ]]; then
22
+ # override the original options
23
+ _shtab_gpustat_options=(${words[CURRENT - 1]} $_shtab_gpustat_options)
24
+ _arguments -C $_shtab_gpustat_options
25
+ else
26
+ eval "${@[-1]}"
27
+ fi
28
+ }
29
+ '''
30
+ }
31
+
32
+
33
+ def zsh_choices_to_complete(choices, tag='', description=''):
34
+ '''Change choices to complete for zsh.
35
+
36
+ https://github.com/zsh-users/zsh/blob/master/Etc/completion-style-guide#L224
37
+ '''
38
+ complete = 'compadd - ' + ' '.join(filter(len, choices))
39
+ if description == '':
40
+ description = tag
41
+ if tag != '':
42
+ complete = '_wanted ' + tag + ' expl ' + description + ' ' + complete
43
+ return complete
44
+
45
+
46
+ def get_complete_for_one_or_zero(input):
47
+ '''Get shell complete for nargs='?'. Now only support zsh.'''
48
+ output = {}
49
+ for sh, complete in input.items():
50
+ if sh == 'zsh':
51
+ output[sh] = "_complete_for_one_or_zero '" + complete + "'"
52
+ return output
53
+
54
+
55
+ def print_gpustat(*, id=None, json=False, debug=False, **kwargs):
56
+ '''Display the GPU query results into standard output.'''
57
+ try:
58
+ gpu_stats = GPUStatCollection.new_query(debug=debug, id=id)
59
+ except Exception as e:
60
+ sys.stderr.write('Error on querying NVIDIA devices. '
61
+ 'Use --debug flag to see more details.\n')
62
+ term = Terminal(stream=sys.stderr)
63
+ sys.stderr.write(term.red(str(e)) + '\n')
64
+
65
+ if debug:
66
+ sys.stderr.write('\n')
67
+ try:
68
+ import traceback
69
+ traceback.print_exc(file=sys.stderr)
70
+ except Exception:
71
+ # NVMLError can't be processed by traceback:
72
+ # https://bugs.python.org/issue28603
73
+ # as a workaround, simply re-throw the exception
74
+ raise e
75
+
76
+ sys.stderr.flush()
77
+ sys.exit(1)
78
+
79
+ if json:
80
+ gpu_stats.print_json(sys.stdout)
81
+ else:
82
+ gpu_stats.print_formatted(sys.stdout, **kwargs)
83
+
84
+
85
+ def loop_gpustat(interval=1.0, **kwargs):
86
+ term = Terminal()
87
+
88
+ with term.fullscreen():
89
+ while 1:
90
+ try:
91
+ query_start = time.time()
92
+
93
+ # Move cursor to (0, 0) but do not restore original cursor loc
94
+ print(term.move(0, 0), end='')
95
+ print_gpustat(eol_char=term.clear_eol + os.linesep, **kwargs)
96
+ print(term.clear_eos, end='')
97
+
98
+ query_duration = time.time() - query_start
99
+ sleep_duration = interval - query_duration
100
+ if sleep_duration > 0:
101
+ time.sleep(sleep_duration)
102
+ except KeyboardInterrupt:
103
+ return 0
104
+
105
+
106
+ def main(*argv):
107
+ if not argv:
108
+ argv = list(sys.argv)
109
+
110
+ # attach SIGPIPE handler to properly handle broken pipe
111
+ try: # sigpipe not available under windows. just ignore in this case
112
+ import signal
113
+ signal.signal(signal.SIGPIPE, signal.SIG_DFL)
114
+ except Exception as e:
115
+ pass
116
+ # arguments to gpustat
117
+ import argparse
118
+ try:
119
+ import shtab
120
+ except ImportError:
121
+ from . import _shtab as shtab
122
+ parser = argparse.ArgumentParser('gpustat')
123
+ shtab.add_argument_to(parser, preamble=SHTAB_PREAMBLE)
124
+
125
+ def nonnegative_int(value):
126
+ value = int(value)
127
+ if value < 0:
128
+ raise argparse.ArgumentTypeError(
129
+ "Only non-negative integers are allowed.")
130
+ return value
131
+
132
+ parser_color = parser.add_mutually_exclusive_group()
133
+ parser_color.add_argument('--force-color', '--color', action='store_true',
134
+ help='Force to output with colors')
135
+ parser_color.add_argument('--no-color', action='store_true',
136
+ help='Suppress colored output')
137
+ parser.add_argument('--id', help='Target a specific GPU (index).')
138
+ parser.add_argument('-a', '--show-all', action='store_true',
139
+ help='Display all gpu properties above')
140
+ parser.add_argument('-c', '--show-cmd', action='store_true',
141
+ help='Display cmd name of running process')
142
+ parser.add_argument(
143
+ '-f', '--show-full-cmd', action='store_true', default=False,
144
+ help='Display full command and cpu stats of running process'
145
+ )
146
+ parser.add_argument('-u', '--show-user', action='store_true',
147
+ help='Display username of running process')
148
+ parser.add_argument('-p', '--show-pid', action='store_true',
149
+ help='Display PID of running process')
150
+ parser.add_argument('-F', '--show-fan-speed', '--show-fan',
151
+ action='store_true', help='Display GPU fan speed')
152
+ codec_choices = ['', 'enc', 'dec', 'enc,dec']
153
+ parser.add_argument(
154
+ '-e', '--show-codec', nargs='?', const='enc,dec', default='',
155
+ choices=codec_choices,
156
+ help='Show encoder/decoder utilization'
157
+ ).complete = get_complete_for_one_or_zero( # type: ignore
158
+ {'zsh': zsh_choices_to_complete(codec_choices, 'codec')}
159
+ )
160
+ power_choices = ['', 'draw', 'limit', 'draw,limit', 'limit,draw']
161
+ parser.add_argument(
162
+ '-P', '--show-power', nargs='?', const='draw,limit',
163
+ choices=power_choices,
164
+ help='Show GPU power usage or draw (and/or limit)'
165
+ ).complete = get_complete_for_one_or_zero( # type: ignore
166
+ {'zsh': zsh_choices_to_complete(power_choices, 'power')}
167
+ )
168
+ parser.add_argument('--json', action='store_true', default=False,
169
+ help='Print all the information in JSON format')
170
+ parser.add_argument(
171
+ '-i', '--interval', '--watch', nargs='?', type=float, default=0,
172
+ help='Use watch mode if given; seconds to wait between updates'
173
+ ).complete = get_complete_for_one_or_zero({'zsh': '_numbers float'}) # type: ignore
174
+ parser.add_argument(
175
+ '--no-header', dest='show_header', action='store_false', default=True,
176
+ help='Suppress header message'
177
+ )
178
+ parser.add_argument(
179
+ '--gpuname-width', type=nonnegative_int, default=None,
180
+ help='The width at which GPU names will be displayed.'
181
+ )
182
+ parser.add_argument(
183
+ '--debug', action='store_true', default=False,
184
+ help='Allow to print additional informations for debugging.'
185
+ )
186
+ parser.add_argument(
187
+ '--no-processes', dest='no_processes', action='store_true',
188
+ help='Do not display running process information (memory, user, etc.)'
189
+ )
190
+ parser.add_argument('-v', '--version', action='version',
191
+ version=('gpustat %s' % __version__))
192
+ args = parser.parse_args(argv[1:])
193
+ # TypeError: GPUStatCollection.print_formatted() got an unexpected keyword argument 'print_completion'
194
+ with suppress(AttributeError):
195
+ del args.print_completion # type: ignore
196
+ if args.show_all:
197
+ args.show_cmd = True
198
+ args.show_user = True
199
+ args.show_pid = True
200
+ args.show_fan_speed = True
201
+ args.show_codec = 'enc,dec'
202
+ args.show_power = 'draw,limit'
203
+ del args.show_all
204
+
205
+ if args.interval is None: # with default value
206
+ args.interval = 1.0
207
+ if args.interval > 0:
208
+ args.interval = max(0.1, args.interval)
209
+ if args.json:
210
+ sys.stderr.write("Error: --json and --interval/-i "
211
+ "can't be used together.\n")
212
+ sys.exit(1)
213
+
214
+ loop_gpustat(**vars(args))
215
+ else:
216
+ del args.interval
217
+ print_gpustat(**vars(args))
218
+
219
+
220
+ if __name__ == '__main__':
221
+ main(*sys.argv)
vllm/lib/python3.10/site-packages/gpustat/core.py ADDED
@@ -0,0 +1,764 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ """
4
+ Implementation of gpustat
5
+
6
+ @author Jongwook Choi
7
+ @url https://github.com/wookayin/gpustat
8
+ """
9
+
10
+ from typing import Sequence
11
+ import json
12
+ import locale
13
+ import os.path
14
+ import platform
15
+ import sys
16
+ import time
17
+ from datetime import datetime
18
+ from io import StringIO
19
+
20
+ import psutil
21
+ from blessed import Terminal
22
+
23
+ import gpustat.util as util
24
+ from gpustat.nvml import pynvml as N
25
+
26
+
27
+ NOT_SUPPORTED = 'Not Supported'
28
+ MB = 1024 * 1024
29
+
30
+ DEFAULT_GPUNAME_WIDTH = 16
31
+
32
+ IS_WINDOWS = 'windows' in platform.platform().lower()
33
+
34
+
35
+ class GPUStat(object):
36
+
37
+ def __init__(self, entry):
38
+ if not isinstance(entry, dict):
39
+ raise TypeError(
40
+ 'entry should be a dict, {} given'.format(type(entry))
41
+ )
42
+ self.entry = entry
43
+
44
+ def __repr__(self):
45
+ return self.print_to(StringIO()).getvalue()
46
+
47
+ def keys(self):
48
+ return self.entry.keys()
49
+
50
+ def __getitem__(self, key):
51
+ return self.entry[key]
52
+
53
+ @property
54
+ def available(self):
55
+ return True
56
+
57
+ @property
58
+ def index(self):
59
+ """
60
+ Returns the index of GPU (as in nvidia-smi).
61
+ """
62
+ return self.entry['index']
63
+
64
+ @property
65
+ def uuid(self):
66
+ """
67
+ Returns the uuid returned by nvidia-smi,
68
+ e.g. GPU-12345678-abcd-abcd-uuid-123456abcdef
69
+ """
70
+ return self.entry['uuid']
71
+
72
+ @property
73
+ def name(self):
74
+ """
75
+ Returns the name of GPU card (e.g. Geforce Titan X)
76
+ """
77
+ return self.entry['name']
78
+
79
+ @property
80
+ def memory_total(self):
81
+ """
82
+ Returns the total memory (in MB) as an integer.
83
+ """
84
+ return int(self.entry['memory.total'])
85
+
86
+ @property
87
+ def memory_used(self):
88
+ """
89
+ Returns the occupied memory (in MB) as an integer.
90
+ """
91
+ return int(self.entry['memory.used'])
92
+
93
+ @property
94
+ def memory_free(self):
95
+ """
96
+ Returns the free (available) memory (in MB) as an integer.
97
+ """
98
+ v = self.memory_total - self.memory_used
99
+ return max(v, 0)
100
+
101
+ @property
102
+ def memory_available(self):
103
+ """
104
+ Returns the available memory (in MB) as an integer.
105
+ Alias of memory_free.
106
+ """
107
+ return self.memory_free
108
+
109
+ @property
110
+ def temperature(self):
111
+ """
112
+ Returns the temperature (in celcius) of GPU as an integer,
113
+ or None if the information is not available.
114
+ """
115
+ v = self.entry['temperature.gpu']
116
+ return int(v) if v is not None else None
117
+
118
+ @property
119
+ def fan_speed(self):
120
+ """
121
+ Returns the fan speed percentage (0-100) of maximum intended speed
122
+ as an integer, or None if the information is not available.
123
+ """
124
+ v = self.entry['fan.speed']
125
+ return int(v) if v is not None else None
126
+
127
+ @property
128
+ def utilization(self):
129
+ """
130
+ Returns the GPU utilization (in percentile),
131
+ or None if the information is not available.
132
+ """
133
+ v = self.entry['utilization.gpu']
134
+ return int(v) if v is not None else None
135
+
136
+ @property
137
+ def utilization_enc(self):
138
+ """
139
+ Returns the GPU encoder utilization (in percentile),
140
+ or None if the information is not available.
141
+ """
142
+ v = self.entry['utilization.enc']
143
+ return int(v) if v is not None else None
144
+
145
+ @property
146
+ def utilization_dec(self):
147
+ """
148
+ Returns the GPU decoder utilization (in percentile),
149
+ or None if the information is not available.
150
+ """
151
+ v = self.entry['utilization.dec']
152
+ return int(v) if v is not None else None
153
+
154
+ @property
155
+ def power_draw(self):
156
+ """
157
+ Returns the GPU power usage in Watts,
158
+ or None if the information is not available.
159
+ """
160
+ v = self.entry['power.draw']
161
+ return int(v) if v is not None else None
162
+
163
+ @property
164
+ def power_limit(self):
165
+ """
166
+ Returns the (enforced) GPU power limit in Watts,
167
+ or None if the information is not available.
168
+ """
169
+ v = self.entry['enforced.power.limit']
170
+ return int(v) if v is not None else None
171
+
172
+ @property
173
+ def processes(self):
174
+ """
175
+ Get the list of running processes on the GPU.
176
+ """
177
+ return self.entry['processes']
178
+
179
+ def print_to(self, fp, *,
180
+ with_colors=True, # deprecated arg
181
+ show_cmd=False,
182
+ show_full_cmd=False,
183
+ no_processes=False,
184
+ show_user=False,
185
+ show_pid=False,
186
+ show_fan_speed=None,
187
+ show_codec="",
188
+ show_power=None,
189
+ gpuname_width=None,
190
+ eol_char=os.linesep,
191
+ term=None,
192
+ ):
193
+ if term is None:
194
+ term = Terminal(stream=sys.stdout)
195
+
196
+ # color settings
197
+ colors = {}
198
+
199
+ def _conditional(cond_fn, true_value, false_value,
200
+ error_value=term.bold_black):
201
+ try:
202
+ return cond_fn() and true_value or false_value
203
+ except Exception:
204
+ return error_value
205
+
206
+ _ENC_THRESHOLD = 50
207
+
208
+ colors['C0'] = term.normal
209
+ colors['C1'] = term.cyan
210
+ colors['CBold'] = term.bold
211
+ colors['CName'] = _conditional(lambda: self.available,
212
+ term.blue, term.red)
213
+ colors['CTemp'] = _conditional(lambda: self.temperature < 50,
214
+ term.red, term.bold_red)
215
+ colors['FSpeed'] = _conditional(lambda: self.fan_speed < 30,
216
+ term.cyan, term.bold_cyan)
217
+ colors['CMemU'] = _conditional(lambda: self.available,
218
+ term.bold_yellow, term.bold_black)
219
+ colors['CMemT'] = _conditional(lambda: self.available,
220
+ term.yellow, term.bold_black)
221
+ colors['CMemP'] = term.yellow
222
+ colors['CCPUMemU'] = term.yellow
223
+ colors['CUser'] = term.bold_black # gray
224
+ colors['CUtil'] = _conditional(lambda: self.utilization < 30,
225
+ term.green, term.bold_green)
226
+ colors['CUtilEnc'] = _conditional(
227
+ lambda: self.utilization_enc < _ENC_THRESHOLD,
228
+ term.green, term.bold_green)
229
+ colors['CUtilDec'] = _conditional(
230
+ lambda: self.utilization_dec < _ENC_THRESHOLD,
231
+ term.green, term.bold_green)
232
+ colors['CCPUUtil'] = term.green
233
+ colors['CPowU'] = _conditional(
234
+ lambda: (self.power_limit is not None and
235
+ float(self.power_draw) / self.power_limit < 0.4),
236
+ term.magenta, term.bold_magenta
237
+ )
238
+ colors['CPowL'] = term.magenta
239
+ colors['CCmd'] = term.color(24) # a bit dark
240
+
241
+ if not with_colors:
242
+ for k in list(colors.keys()):
243
+ colors[k] = ''
244
+
245
+ def _repr(v, none_value='??'):
246
+ return none_value if v is None else v
247
+
248
+ # build one-line display information
249
+ # we want power use optional, but if deserves being grouped with
250
+ # temperature and utilization
251
+ reps = u"%(C1)s[{entry[index]}]%(C0)s "
252
+ if gpuname_width is None or gpuname_width != 0:
253
+ reps += u"%(CName)s{entry_name:{gpuname_width}}%(C0)s |"
254
+ reps += u"%(CTemp)s{entry[temperature.gpu]:>3}°C%(C0)s, "
255
+
256
+ if show_fan_speed:
257
+ reps += "%(FSpeed)s{entry[fan.speed]:>3} %%%(C0)s, "
258
+
259
+ reps += "%(CUtil)s{entry[utilization.gpu]:>3} %%%(C0)s"
260
+
261
+ if show_codec:
262
+ codec_info = []
263
+ if "enc" in show_codec:
264
+ codec_info.append(
265
+ "%(CBold)sE: %(C0)s"
266
+ "%(CUtilEnc)s{entry[utilization.enc]:>3} %%%(C0)s")
267
+ if "dec" in show_codec:
268
+ codec_info.append(
269
+ "%(CBold)sD: %(C0)s"
270
+ "%(CUtilDec)s{entry[utilization.dec]:>3} %%%(C0)s")
271
+ reps += " ({})".format(" ".join(codec_info))
272
+
273
+ if show_power:
274
+ reps += ", %(CPowU)s{entry[power.draw]:>3}%(C0)s "
275
+ if show_power is True or 'limit' in show_power:
276
+ reps += "/ %(CPowL)s{entry[enforced.power.limit]:>3}%(C0)s "
277
+ reps += "%(CPowL)sW%(C0)s"
278
+ else:
279
+ reps += "%(CPowU)sW%(C0)s"
280
+
281
+ reps += " | %(C1)s%(CMemU)s{entry[memory.used]:>5}%(C0)s " \
282
+ "/ %(CMemT)s{entry[memory.total]:>5}%(C0)s MB"
283
+ reps = (reps) % colors
284
+
285
+ class entry_repr_accessor:
286
+ def __init__(self, entry):
287
+ self.entry = entry
288
+ def __getitem__(self, key):
289
+ return _repr(self.entry[key])
290
+
291
+ reps = reps.format(
292
+ entry=entry_repr_accessor(self.entry),
293
+ entry_name=util.shorten_left(
294
+ self.entry["name"], width=gpuname_width, placeholder='…'),
295
+ gpuname_width=gpuname_width or DEFAULT_GPUNAME_WIDTH
296
+ )
297
+
298
+ # Add " |" only if processes information is to be added.
299
+ if not no_processes:
300
+ reps += " |"
301
+
302
+ def process_repr(p):
303
+ r = ''
304
+ if not show_cmd or show_user:
305
+ r += "{CUser}{}{C0}".format(
306
+ _repr(p['username'], '--'), **colors
307
+ )
308
+ if show_cmd:
309
+ if r:
310
+ r += ':'
311
+ r += "{C1}{}{C0}".format(
312
+ _repr(p.get('command', p['pid']), '--'), **colors
313
+ )
314
+
315
+ if show_pid:
316
+ r += ("/%s" % _repr(p['pid'], '--'))
317
+ r += '({CMemP}{}M{C0})'.format(
318
+ _repr(p['gpu_memory_usage'], '?'), **colors
319
+ )
320
+ return r
321
+
322
+ def full_process_info(p):
323
+ r = "{C0} ├─ {:>6} ".format(
324
+ _repr(p['pid'], '--'), **colors
325
+ )
326
+ r += "{C0}({CCPUUtil}{:4.0f}%{C0}, {CCPUMemU}{:>6}{C0})".format(
327
+ _repr(p['cpu_percent'], '--'),
328
+ util.bytes2human(_repr(p['cpu_memory_usage'], 0)), **colors
329
+ )
330
+ full_command_pretty = util.prettify_commandline(
331
+ p['full_command'], colors['C1'], colors['CCmd'])
332
+ r += "{C0}: {CCmd}{}{C0}".format(
333
+ _repr(full_command_pretty, '?'),
334
+ **colors
335
+ )
336
+ return r
337
+
338
+ processes = self.entry['processes']
339
+ full_processes = []
340
+ if processes is None and not no_processes:
341
+ # None (not available)
342
+ reps += ' ({})'.format(NOT_SUPPORTED)
343
+ elif not no_processes:
344
+ for p in processes:
345
+ reps += ' ' + process_repr(p)
346
+ if show_full_cmd:
347
+ full_processes.append(eol_char + full_process_info(p))
348
+ if show_full_cmd and full_processes:
349
+ full_processes[-1] = full_processes[-1].replace('├', '└', 1)
350
+ reps += ''.join(full_processes)
351
+ fp.write(reps)
352
+ return fp
353
+
354
+ def jsonify(self):
355
+ o = self.entry.copy()
356
+ if self.entry['processes'] is not None:
357
+ o['processes'] = [{k: v for (k, v) in p.items() if k != 'gpu_uuid'}
358
+ for p in self.entry['processes']]
359
+ return o
360
+
361
+
362
+ class InvalidGPU(GPUStat):
363
+ class FallbackDict(dict):
364
+ def __missing__(self, key):
365
+ return "?"
366
+
367
+ def __init__(self, gpu_index, message, ex):
368
+ super().__init__(self.FallbackDict(
369
+ index=gpu_index,
370
+ name=message,
371
+ processes=None
372
+ ))
373
+ self.exception = ex
374
+
375
+ @property
376
+ def available(self):
377
+ return False
378
+
379
+
380
+ class GPUStatCollection(Sequence[GPUStat]):
381
+
382
+ global_processes = {}
383
+
384
+ def __init__(self, gpu_list, driver_version=None):
385
+ self.gpus = gpu_list
386
+
387
+ # attach additional system information
388
+ self.hostname = platform.node()
389
+ self.query_time = datetime.now()
390
+ self.driver_version = driver_version
391
+
392
+ @staticmethod
393
+ def clean_processes():
394
+ for pid in list(GPUStatCollection.global_processes.keys()):
395
+ if not psutil.pid_exists(pid):
396
+ del GPUStatCollection.global_processes[pid]
397
+
398
+ @staticmethod
399
+ def new_query(debug=False, id=None) -> 'GPUStatCollection':
400
+ """Query the information of all the GPUs on local machine"""
401
+
402
+ N.nvmlInit()
403
+ log = util.DebugHelper()
404
+
405
+ def _decode(b):
406
+ if isinstance(b, bytes):
407
+ return b.decode('utf-8') # for python3, to unicode
408
+ return b
409
+
410
+ def get_gpu_info(handle):
411
+ """Get one GPU information specified by nvml handle"""
412
+
413
+ def safepcall(fn, error_value):
414
+ # Ignore the exception from psutil when the process is gone
415
+ # at the moment of querying. See #144.
416
+ return util.safecall(
417
+ fn, error_value=error_value,
418
+ exc_types=(psutil.AccessDenied, psutil.NoSuchProcess,
419
+ FileNotFoundError))
420
+
421
+ def get_process_info(nv_process):
422
+ """Get the process information of specific pid"""
423
+ process = {}
424
+ if nv_process.pid not in GPUStatCollection.global_processes:
425
+ GPUStatCollection.global_processes[nv_process.pid] = \
426
+ psutil.Process(pid=nv_process.pid)
427
+ ps_process: psutil.Process = GPUStatCollection.global_processes[nv_process.pid]
428
+
429
+ # TODO: ps_process is being cached, but the dict below is not.
430
+ process['username'] = safepcall(ps_process.username, '?')
431
+ # cmdline returns full path;
432
+ # as in `ps -o comm`, get short cmdnames.
433
+ _cmdline = safepcall(ps_process.cmdline, [])
434
+ if not _cmdline:
435
+ # sometimes, zombie or unknown (e.g. [kworker/8:2H])
436
+ process['command'] = '?'
437
+ process['full_command'] = ['?']
438
+ else:
439
+ process['command'] = os.path.basename(_cmdline[0])
440
+ process['full_command'] = _cmdline
441
+ # Bytes to MBytes
442
+ # if drivers are not TTC this will be None.
443
+ usedmem = nv_process.usedGpuMemory // MB if \
444
+ nv_process.usedGpuMemory else None
445
+ process['gpu_memory_usage'] = usedmem
446
+
447
+ process['cpu_percent'] = safepcall(ps_process.cpu_percent, 0.0)
448
+ process['cpu_memory_usage'] = safepcall(
449
+ lambda: round((ps_process.memory_percent() / 100.0) *
450
+ psutil.virtual_memory().total),
451
+ 0.0)
452
+
453
+ process['pid'] = nv_process.pid
454
+ return process
455
+
456
+ name = _decode(N.nvmlDeviceGetName(handle))
457
+ uuid = _decode(N.nvmlDeviceGetUUID(handle))
458
+
459
+ try:
460
+ temperature = N.nvmlDeviceGetTemperature(
461
+ handle, N.NVML_TEMPERATURE_GPU
462
+ )
463
+ except N.NVMLError as e:
464
+ log.add_exception("temperature", e)
465
+ temperature = None # Not supported
466
+
467
+ try:
468
+ fan_speed = N.nvmlDeviceGetFanSpeed(handle)
469
+ except N.NVMLError as e:
470
+ log.add_exception("fan_speed", e)
471
+ fan_speed = None # Not supported
472
+
473
+ try:
474
+ # memory: in Bytes
475
+ # Note that this is a compat-patched API (see gpustat.nvml)
476
+ memory = N.nvmlDeviceGetMemoryInfo(handle)
477
+ except N.NVMLError as e:
478
+ log.add_exception("memory", e)
479
+ memory = None # Not supported
480
+
481
+ try:
482
+ utilization = N.nvmlDeviceGetUtilizationRates(handle)
483
+ except N.NVMLError as e:
484
+ log.add_exception("utilization", e)
485
+ utilization = None # Not supported
486
+
487
+ try:
488
+ utilization_enc = N.nvmlDeviceGetEncoderUtilization(handle)
489
+ except N.NVMLError as e:
490
+ log.add_exception("utilization_enc", e)
491
+ utilization_enc = None # Not supported
492
+
493
+ try:
494
+ utilization_dec = N.nvmlDeviceGetDecoderUtilization(handle)
495
+ except N.NVMLError as e:
496
+ log.add_exception("utilization_dec", e)
497
+ utilization_dec = None # Not supported
498
+
499
+ try:
500
+ power = N.nvmlDeviceGetPowerUsage(handle)
501
+ except N.NVMLError as e:
502
+ log.add_exception("power", e)
503
+ power = None
504
+
505
+ try:
506
+ power_limit = N.nvmlDeviceGetEnforcedPowerLimit(handle)
507
+ except N.NVMLError as e:
508
+ log.add_exception("power_limit", e)
509
+ power_limit = None
510
+
511
+ try:
512
+ nv_comp_processes = \
513
+ N.nvmlDeviceGetComputeRunningProcesses(handle)
514
+ except N.NVMLError as e:
515
+ log.add_exception("compute_processes", e)
516
+ nv_comp_processes = None # Not supported
517
+ try:
518
+ nv_graphics_processes = \
519
+ N.nvmlDeviceGetGraphicsRunningProcesses(handle)
520
+ except N.NVMLError as e:
521
+ log.add_exception("graphics_processes", e)
522
+ nv_graphics_processes = None # Not supported
523
+
524
+ if nv_comp_processes is None and nv_graphics_processes is None:
525
+ processes = None
526
+ else:
527
+ processes = []
528
+ nv_comp_processes = nv_comp_processes or []
529
+ nv_graphics_processes = nv_graphics_processes or []
530
+ # A single process might run in both of graphics and compute mode,
531
+ # However we will display the process only once
532
+ seen_pids = set()
533
+ for nv_process in nv_comp_processes + nv_graphics_processes:
534
+ if nv_process.pid in seen_pids:
535
+ continue
536
+ seen_pids.add(nv_process.pid)
537
+ try:
538
+ process = get_process_info(nv_process)
539
+ processes.append(process)
540
+ except psutil.NoSuchProcess:
541
+ # TODO: add some reminder for NVML broken context
542
+ # e.g. nvidia-smi reset or reboot the system
543
+ pass
544
+ except psutil.AccessDenied:
545
+ pass
546
+ except FileNotFoundError:
547
+ # Ignore the exception which probably has occured
548
+ # from psutil, due to a non-existent PID (see #95).
549
+ # The exception should have been translated, but
550
+ # there appears to be a bug of psutil. It is unlikely
551
+ # FileNotFoundError is thrown in different situations.
552
+ pass
553
+
554
+ # TODO: Do not block if full process info is not requested
555
+ time.sleep(0.1)
556
+ for process in processes:
557
+ pid = process['pid']
558
+ cache_process: psutil.Process = GPUStatCollection.global_processes[pid]
559
+ process['cpu_percent'] = safepcall(cache_process.cpu_percent, 0)
560
+
561
+ index = N.nvmlDeviceGetIndex(handle)
562
+
563
+ # GPU Info.
564
+ # We use the same key/spec as per `nvidia-smi --query-help-gpu`
565
+ gpu_info = {
566
+ 'index': index,
567
+ 'uuid': uuid,
568
+ 'name': name,
569
+ 'temperature.gpu': temperature,
570
+ 'fan.speed': fan_speed,
571
+ 'utilization.gpu': utilization.gpu if utilization else None,
572
+ 'utilization.enc':
573
+ utilization_enc[0] if utilization_enc else None,
574
+ 'utilization.dec':
575
+ utilization_dec[0] if utilization_dec else None,
576
+ 'power.draw': power // 1000 if power is not None else None,
577
+ 'enforced.power.limit': power_limit // 1000
578
+ if power_limit is not None else None,
579
+ # Convert bytes into MBytes
580
+ 'memory.used': memory.used // MB if memory else None,
581
+ 'memory.total': memory.total // MB if memory else None,
582
+ 'processes': processes,
583
+ }
584
+ GPUStatCollection.clean_processes()
585
+ return gpu_info
586
+
587
+ # 1. get the list of gpu and status
588
+ gpu_list = []
589
+ device_count = N.nvmlDeviceGetCount()
590
+
591
+ if id is None:
592
+ gpus_to_query = range(device_count)
593
+ elif isinstance(id, str):
594
+ gpus_to_query = [int(i) for i in id.split(',')]
595
+ elif isinstance(id, Sequence):
596
+ gpus_to_query = [int(i) for i in id]
597
+ else:
598
+ raise TypeError(f"Unknown id: {id}")
599
+
600
+ for index in gpus_to_query:
601
+ try:
602
+ handle = N.nvmlDeviceGetHandleByIndex(index)
603
+ gpu_info = get_gpu_info(handle)
604
+ gpu_stat = GPUStat(gpu_info)
605
+ except N.NVMLError_Unknown as e:
606
+ gpu_stat = InvalidGPU(index, "((Unknown Error))", e)
607
+ except N.NVMLError_GpuIsLost as e:
608
+ gpu_stat = InvalidGPU(index, "((GPU is lost))", e)
609
+
610
+ if isinstance(gpu_stat, InvalidGPU):
611
+ log.add_exception("GPU %d" % index, gpu_stat.exception)
612
+ gpu_list.append(gpu_stat)
613
+
614
+ # 2. additional info (driver version, etc).
615
+ try:
616
+ driver_version = _decode(N.nvmlSystemGetDriverVersion())
617
+ except N.NVMLError as e:
618
+ log.add_exception("driver_version", e)
619
+ driver_version = None # N/A
620
+
621
+ if debug:
622
+ log.report_summary()
623
+
624
+ N.nvmlShutdown()
625
+ return GPUStatCollection(gpu_list, driver_version=driver_version)
626
+
627
+ def __len__(self):
628
+ return len(self.gpus)
629
+
630
+ def __iter__(self):
631
+ return iter(self.gpus)
632
+
633
+ def __getitem__(self, index):
634
+ return self.gpus[index]
635
+
636
+ def __repr__(self):
637
+ s = 'GPUStatCollection(host=%s, [\n' % self.hostname
638
+ s += '\n'.join(' ' + str(g) for g in self.gpus)
639
+ s += '\n])'
640
+ return s
641
+
642
+ # --- Printing Functions ---
643
+
644
+ def print_formatted(self, fp=sys.stdout, *,
645
+ force_color=False, no_color=False,
646
+ show_cmd=False, show_full_cmd=False, show_user=False,
647
+ show_pid=False, show_fan_speed=None,
648
+ show_codec="", show_power=None,
649
+ gpuname_width=None, show_header=True,
650
+ no_processes=False,
651
+ eol_char=os.linesep,
652
+ ):
653
+ # ANSI color configuration
654
+ if force_color and no_color:
655
+ raise ValueError("--color and --no_color can't"
656
+ " be used at the same time")
657
+
658
+ if force_color:
659
+ TERM = os.getenv('TERM') or 'xterm-256color'
660
+ t_color = Terminal(kind=TERM, force_styling=True)
661
+
662
+ # workaround of issue #32 (watch doesn't recognize sgr0 characters)
663
+ t_color._normal = u'\x1b[0;10m'
664
+ elif no_color:
665
+ t_color = Terminal(force_styling=None)
666
+ else:
667
+ t_color = Terminal() # auto, depending on isatty
668
+
669
+ # appearance settings
670
+ if gpuname_width is None:
671
+ gpuname_width = max([len(g.entry['name']) for g in self] + [0])
672
+
673
+ # header
674
+ if show_header:
675
+ if IS_WINDOWS:
676
+ # no localization is available; just use a reasonable default
677
+ # same as str(timestr) but without ms
678
+ timestr = self.query_time.strftime('%Y-%m-%d %H:%M:%S')
679
+ else:
680
+ time_format = locale.nl_langinfo(locale.D_T_FMT)
681
+ timestr = self.query_time.strftime(time_format)
682
+ header_template = '{t.bold_white}{hostname:{width}}{t.normal} '
683
+ header_template += '{timestr} '
684
+ header_template += '{t.bold_black}{driver_version}{t.normal}'
685
+
686
+ header_msg = header_template.format(
687
+ hostname=self.hostname,
688
+ width=(gpuname_width or DEFAULT_GPUNAME_WIDTH) + 3, # len("[?]")
689
+ timestr=timestr,
690
+ driver_version=self.driver_version,
691
+ t=t_color,
692
+ )
693
+
694
+ fp.write(header_msg.strip())
695
+ fp.write(eol_char)
696
+
697
+ # body
698
+ for g in self:
699
+ g.print_to(fp,
700
+ show_cmd=show_cmd,
701
+ show_full_cmd=show_full_cmd,
702
+ no_processes=no_processes,
703
+ show_user=show_user,
704
+ show_pid=show_pid,
705
+ show_fan_speed=show_fan_speed,
706
+ show_codec=show_codec,
707
+ show_power=show_power,
708
+ gpuname_width=gpuname_width,
709
+ eol_char=eol_char,
710
+ term=t_color)
711
+ fp.write(eol_char)
712
+
713
+ if len(self.gpus) == 0:
714
+ print(t_color.yellow("(No GPUs are available)"))
715
+
716
+ fp.flush()
717
+
718
+ def jsonify(self):
719
+ return {
720
+ 'hostname': self.hostname,
721
+ 'driver_version': self.driver_version,
722
+ 'query_time': self.query_time,
723
+ "gpus": [g.jsonify() for g in self]
724
+ }
725
+
726
+ def print_json(self, fp=sys.stdout):
727
+ def date_handler(obj):
728
+ if hasattr(obj, 'isoformat'):
729
+ return obj.isoformat()
730
+ else:
731
+ raise TypeError(type(obj))
732
+
733
+ o = self.jsonify()
734
+ json.dump(o, fp, indent=4, separators=(',', ': '),
735
+ default=date_handler)
736
+ fp.write(os.linesep)
737
+ fp.flush()
738
+
739
+
740
+ def new_query() -> GPUStatCollection:
741
+ '''
742
+ Obtain a new GPUStatCollection instance by querying nvidia-smi
743
+ to get the list of GPUs and running process information.
744
+ '''
745
+ return GPUStatCollection.new_query()
746
+
747
+
748
+ def gpu_count() -> int:
749
+ '''Return the number of available GPUs in the system.'''
750
+ try:
751
+ N.nvmlInit()
752
+ return N.nvmlDeviceGetCount()
753
+ except N.NVMLError:
754
+ return 0 # fallback
755
+ finally:
756
+ try:
757
+ N.nvmlShutdown()
758
+ except N.NVMLError:
759
+ pass
760
+
761
+
762
+ def is_available() -> bool:
763
+ '''Return True if the NVML library and GPU devices are available.'''
764
+ return gpu_count() > 0
vllm/lib/python3.10/site-packages/gpustat/nvml.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Imports pynvml with sanity checks and custom patches."""
2
+
3
+ import warnings
4
+ import functools
5
+ import os
6
+ import sys
7
+ import textwrap
8
+
9
+ # If this environment variable is set, we will bypass pynvml version validation
10
+ # so that legacy pynvml (nvidia-ml-py3) can be used. This would be useful
11
+ # in a case where there are conflicts on pynvml dependencies.
12
+ # However, beware that pynvml might produce wrong results (see #107).
13
+ ALLOW_LEGACY_PYNVML = os.getenv("ALLOW_LEGACY_PYNVML", "")
14
+ ALLOW_LEGACY_PYNVML = ALLOW_LEGACY_PYNVML.lower() not in ('false', '0', '')
15
+
16
+
17
+ try:
18
+ # Check pynvml version: we require 11.450.129 or newer.
19
+ # https://github.com/wookayin/gpustat/pull/107
20
+ import pynvml
21
+ if not (
22
+ # Requires nvidia-ml-py >= 11.460.79
23
+ hasattr(pynvml, 'NVML_BRAND_NVIDIA_RTX') or
24
+ # Requires nvidia-ml-py >= 11.450.129, < 11.510.69
25
+ hasattr(pynvml, 'nvmlDeviceGetComputeRunningProcesses_v2')
26
+ ) and not ALLOW_LEGACY_PYNVML:
27
+ raise ImportError("pynvml library is outdated.")
28
+
29
+ if not hasattr(pynvml, '_nvmlGetFunctionPointer'):
30
+ # Unofficial pynvml from @gpuopenanalytics/pynvml, see #153
31
+ import pynvml.nvml as pynvml
32
+
33
+ except (ImportError, SyntaxError, RuntimeError) as e:
34
+ _pynvml = sys.modules.get('pynvml', None)
35
+
36
+ raise ImportError(textwrap.dedent(
37
+ """\
38
+ pynvml is missing or an outdated version is installed.
39
+
40
+ We require nvidia-ml-py>=11.450.129, and the official NVIDIA python bindings
41
+ should be used; neither nvidia-ml-py3 nor gpuopenanalytics/pynvml.
42
+ For more details, please refer to: https://github.com/wookayin/gpustat/issues/107
43
+
44
+ The root cause: """ + str(e) +
45
+ """
46
+
47
+ Your pynvml installation: """ + repr(_pynvml) +
48
+ """
49
+
50
+ -----------------------------------------------------------
51
+ Please reinstall `gpustat`:
52
+
53
+ $ pip install --force-reinstall gpustat
54
+
55
+ If it still does not fix the problem, please uninstall pynvml packages and reinstall nvidia-ml-py manually:
56
+
57
+ $ pip uninstall nvidia-ml-py3 pynvml
58
+ $ pip install --force-reinstall --ignore-installed 'nvidia-ml-py'
59
+ """)) from e
60
+
61
+
62
+ # Monkey-patch nvml due to breaking changes in pynvml.
63
+ # See #107, #141, and test_gpustat.py for more details.
64
+
65
+ _original_nvmlGetFunctionPointer = pynvml._nvmlGetFunctionPointer
66
+ _original_nvmlDeviceGetMemoryInfo = pynvml.nvmlDeviceGetMemoryInfo
67
+
68
+
69
+ class pynvml_monkeypatch:
70
+
71
+ @staticmethod # Note: must be defined as a staticmethod to allow mocking.
72
+ def original_nvmlGetFunctionPointer(name):
73
+ return _original_nvmlGetFunctionPointer(name)
74
+
75
+ FUNCTION_FALLBACKS = {
76
+ # for pynvml._nvmlGetFunctionPointer
77
+ 'nvmlDeviceGetComputeRunningProcesses_v3': 'nvmlDeviceGetComputeRunningProcesses_v2',
78
+ 'nvmlDeviceGetGraphicsRunningProcesses_v3': 'nvmlDeviceGetGraphicsRunningProcesses_v2',
79
+ }
80
+
81
+ @staticmethod
82
+ @functools.wraps(pynvml._nvmlGetFunctionPointer)
83
+ def _nvmlGetFunctionPointer(name):
84
+ """Our monkey-patched pynvml._nvmlGetFunctionPointer().
85
+
86
+ See also:
87
+ test_gpustat::NvidiaDriverMock for test scenarios. See #107.
88
+ """
89
+ M = pynvml_monkeypatch
90
+
91
+ try:
92
+ ret = M.original_nvmlGetFunctionPointer(name)
93
+ return ret
94
+ except pynvml.NVMLError_FunctionNotFound: # type: ignore
95
+ if name in M.FUNCTION_FALLBACKS:
96
+ # Lack of ...Processes_v3 APIs happens for
97
+ # OLD drivers < 510.39.01 && pynvml >= 11.510, where
98
+ # we fallback to v2 APIs. (see #107 for more details)
99
+
100
+ ret = M.original_nvmlGetFunctionPointer(
101
+ M.FUNCTION_FALLBACKS[name]
102
+ )
103
+ # populate the cache, so this handler won't get executed again
104
+ pynvml._nvmlGetFunctionPointer_cache[name] = ret
105
+
106
+ else:
107
+ # Unknown case, cannot handle. re-raise again
108
+ raise
109
+
110
+ return ret
111
+
112
+ @staticmethod # Note: must be defined as a staticmethod to allow mocking.
113
+ def original_nvmlDeviceGetMemoryInfo(*args, **kwargs):
114
+ return _original_nvmlDeviceGetMemoryInfo(*args, **kwargs)
115
+
116
+ has_memoryinfo_v2 = None
117
+
118
+ @staticmethod
119
+ @functools.wraps(pynvml.nvmlDeviceGetMemoryInfo)
120
+ def nvmlDeviceGetMemoryInfo(handle):
121
+ """A patched version of nvmlDeviceGetMemoryInfo.
122
+
123
+ This tries `version=N.nvmlMemory_v2` if the nvmlDeviceGetMemoryInfo_v2
124
+ function is available (for driver >= 515), or fallback to the legacy
125
+ v1 API for (driver < 515) to yield a correct result. See #141.
126
+ """
127
+ M = pynvml_monkeypatch
128
+
129
+ if M.has_memoryinfo_v2 is None:
130
+ try:
131
+ pynvml._nvmlGetFunctionPointer("nvmlDeviceGetMemoryInfo_v2")
132
+ M.has_memoryinfo_v2 = True
133
+ except pynvml.NVMLError_FunctionNotFound: # type: ignore
134
+ M.has_memoryinfo_v2 = False
135
+
136
+ if hasattr(pynvml, 'nvmlMemory_v2'): # pynvml >= 11.510.69
137
+ try:
138
+ memory = M.original_nvmlDeviceGetMemoryInfo(
139
+ handle, version=pynvml.nvmlMemory_v2)
140
+ except pynvml.NVMLError_FunctionNotFound: # type: ignore
141
+ # pynvml >= 11.510 but driver is old (<515.39)
142
+ memory = M.original_nvmlDeviceGetMemoryInfo(handle)
143
+ else:
144
+ if M.has_memoryinfo_v2:
145
+ warnings.warn(
146
+ "Your NVIDIA driver requires a compatible version of "
147
+ "pynvml (>= 11.510.69) installed to display the correct "
148
+ "memory usage information (See #141 for more details). "
149
+ "Please try `pip install --upgrade nvidia-ml-py`.",
150
+ category=UserWarning)
151
+ memory = M.original_nvmlDeviceGetMemoryInfo(handle)
152
+
153
+ return memory
154
+
155
+
156
+ setattr(pynvml, '_nvmlGetFunctionPointer', pynvml_monkeypatch._nvmlGetFunctionPointer)
157
+ setattr(pynvml, 'nvmlDeviceGetMemoryInfo', pynvml_monkeypatch.nvmlDeviceGetMemoryInfo)
158
+
159
+
160
+ __all__ = ['pynvml']
vllm/lib/python3.10/site-packages/gpustat/test_gpustat.py ADDED
@@ -0,0 +1,703 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Unit or integration tests for gpustat
3
+ """
4
+ # flake8: ignore=E501
5
+
6
+ import ctypes
7
+ import os
8
+ import shlex
9
+ import sys
10
+ import types
11
+ from collections import namedtuple
12
+ from io import StringIO
13
+ from typing import Any
14
+
15
+ import psutil
16
+ import pytest
17
+ from mockito import ANY, mock, unstub, when, when2
18
+
19
+ import gpustat
20
+ from gpustat.nvml import pynvml, pynvml_monkeypatch
21
+
22
+ MB = 1024 * 1024
23
+
24
+
25
+ def remove_ansi_codes(s):
26
+ import re
27
+ s = re.compile(r'\x1b[^m]*m').sub('', s)
28
+ s = re.compile(r'\x0f').sub('', s)
29
+ return s
30
+
31
+ # -----------------------------------------------------------------------------
32
+
33
+ mock_gpu_handles = [types.SimpleNamespace(value='mock-handle-%d' % i, index=i)
34
+ for i in range(3)]
35
+
36
+ def _configure_mock(N=pynvml,
37
+ _scenario_nonexistent_pid=False, # GH-95
38
+ _scenario_failing_one_gpu=None, # GH-125, GH-81
39
+ ):
40
+ """Define mock behaviour for pynvml and psutil.{Process,virtual_memory}."""
41
+
42
+ # without following patch, unhashable NVMLError makes unit test crash
43
+ N.NVMLError.__hash__ = lambda _: 0
44
+ assert issubclass(N.NVMLError, BaseException)
45
+
46
+ unstub(N) # reset all the stubs
47
+
48
+ when(N).nvmlInit().thenReturn()
49
+ when(N).nvmlShutdown().thenReturn()
50
+ when(N).nvmlSystemGetDriverVersion().thenReturn('415.27.mock')
51
+
52
+ when(N)._nvmlGetFunctionPointer(...).thenCallOriginalImplementation()
53
+
54
+ NUM_GPUS = 3
55
+ when(N).nvmlDeviceGetCount().thenReturn(NUM_GPUS)
56
+
57
+ def _return_or_raise(v):
58
+ """Return a callable for thenAnswer() to let exceptions re-raised."""
59
+ def _callable(*args, **kwargs):
60
+ del args, kwargs
61
+ if isinstance(v, Exception):
62
+ raise v
63
+ return v
64
+ return _callable
65
+
66
+ for i in range(NUM_GPUS):
67
+ handle = mock_gpu_handles[i]
68
+ if _scenario_failing_one_gpu and i == 2: # see #81, #125
69
+ assert (_scenario_failing_one_gpu is N.NVMLError_Unknown or
70
+ _scenario_failing_one_gpu is N.NVMLError_GpuIsLost)
71
+ handle = _scenario_failing_one_gpu() # see 81
72
+
73
+ when(N).nvmlDeviceGetHandleByIndex(i)\
74
+ .thenAnswer(_return_or_raise(handle))
75
+ when(N).nvmlDeviceGetIndex(handle)\
76
+ .thenReturn(i)
77
+ when(N).nvmlDeviceGetName(handle)\
78
+ .thenReturn({
79
+ 0: 'GeForce GTX TITAN 0',
80
+ 1: 'GeForce GTX TITAN 1',
81
+ 2: 'GeForce RTX 2',
82
+ }[i].encode())
83
+ when(N).nvmlDeviceGetUUID(handle)\
84
+ .thenReturn({
85
+ 0: b'GPU-10fb0fbd-2696-43f3-467f-d280d906a107',
86
+ 1: b'GPU-d1df4664-bb44-189c-7ad0-ab86c8cb30e2',
87
+ 2: b'GPU-50205d95-57b6-f541-2bcb-86c09afed564',
88
+ }[i])
89
+
90
+ when(N).nvmlDeviceGetTemperature(handle, N.NVML_TEMPERATURE_GPU)\
91
+ .thenReturn([80, 36, 71][i])
92
+ when(N).nvmlDeviceGetFanSpeed(handle)\
93
+ .thenReturn([16, 53, 100][i])
94
+ when(N).nvmlDeviceGetPowerUsage(handle)\
95
+ .thenAnswer(_return_or_raise({
96
+ 0: 125000, 1: N.NVMLError_NotSupported(), 2: 250000
97
+ }[i]))
98
+ when(N).nvmlDeviceGetEnforcedPowerLimit(handle)\
99
+ .thenAnswer(_return_or_raise({
100
+ 0: 250000, 1: 250000, 2: N.NVMLError_NotSupported()
101
+ }[i]))
102
+
103
+ # see also: NvidiaDriverMock
104
+ mock_memory_t = namedtuple("Memory_t", ['total', 'used']) # c_nvmlMemory_t
105
+ when(N).nvmlDeviceGetMemoryInfo(handle)\
106
+ .thenAnswer(_return_or_raise({
107
+ 0: mock_memory_t(total=12883853312, used=8000*MB),
108
+ 1: mock_memory_t(total=12781551616, used=9000*MB),
109
+ 2: mock_memory_t(total=12781551616, used=0),
110
+ }[i]))
111
+ # this mock function assumes <510.39 behavior (#141)
112
+ when(N, strict=False)\
113
+ .nvmlDeviceGetMemoryInfo(handle, version=ANY())\
114
+ .thenRaise(N.NVMLError_FunctionNotFound)
115
+
116
+ mock_utilization_t = namedtuple("Utilization_t", ['gpu', 'memory'])
117
+ when(N).nvmlDeviceGetUtilizationRates(handle)\
118
+ .thenAnswer(_return_or_raise({
119
+ 0: mock_utilization_t(gpu=76, memory=0),
120
+ 1: mock_utilization_t(gpu=0, memory=0),
121
+ 2: N.NVMLError_NotSupported(), # Not Supported
122
+ }[i]))
123
+
124
+ when(N).nvmlDeviceGetEncoderUtilization(handle)\
125
+ .thenAnswer(_return_or_raise({
126
+ 0: [88, 167000], # [value, sample_rate]
127
+ 1: [0, 167000], # [value, sample_rate]
128
+ 2: N.NVMLError_NotSupported(), # Not Supported
129
+ }[i]))
130
+ when(N).nvmlDeviceGetDecoderUtilization(handle)\
131
+ .thenAnswer(_return_or_raise({
132
+ 0: [67, 167000], # [value, sample_rate]
133
+ 1: [0, 167000], # [value, sample_rate]
134
+ 2: N.NVMLError_NotSupported(), # Not Supported
135
+ }[i]))
136
+
137
+ # running process information: a bit annoying...
138
+ mock_process_t = namedtuple("Process_t", ['pid', 'usedGpuMemory'])
139
+
140
+ if _scenario_nonexistent_pid:
141
+ mock_processes_gpu2_erratic = [
142
+ mock_process_t(99999, 9999*MB),
143
+ mock_process_t(99995, 9995*MB), # see issue #95
144
+ ]
145
+ else:
146
+ mock_processes_gpu2_erratic = N.NVMLError_NotSupported()
147
+
148
+ # see NvidiaDriverMock as well
149
+ when(N).nvmlDeviceGetComputeRunningProcesses(handle)\
150
+ .thenAnswer(_return_or_raise({
151
+ 0: [mock_process_t(48448, 4000*MB), mock_process_t(153223, 4000*MB)],
152
+ 1: [mock_process_t(192453, 3000*MB), mock_process_t(194826, 6000*MB)],
153
+ 2: mock_processes_gpu2_erratic, # Not Supported or non-existent
154
+ }[i]))
155
+
156
+ when(N).nvmlDeviceGetGraphicsRunningProcesses(handle)\
157
+ .thenAnswer(_return_or_raise({
158
+ 0: [mock_process_t(48448, 4000*MB)],
159
+ 1: [],
160
+ 2: N.NVMLError_NotSupported(),
161
+ }[i]))
162
+
163
+ # for psutil
164
+ mock_pid_map = { # mock/stub information for psutil...
165
+ 48448: ('user1', 'python', 85.25, 3.1415),
166
+ 154213: ('user1', 'caffe', 16.89, 100.00),
167
+ 38310: ('user3', 'python', 26.23, 99.9653),
168
+ 153223: ('user2', 'python', 15.25, 0.0000),
169
+ 194826: ('user3', 'caffe', 0.0, 12.5236),
170
+ 192453: ('user1', 'torch', 123.2, 0.7312),
171
+ }
172
+ assert 99999 not in mock_pid_map, 'scenario_nonexistent_pid'
173
+ assert 99995 not in mock_pid_map, 'scenario_nonexistent_pid (#95)'
174
+
175
+ def _MockedProcess(pid):
176
+ if pid not in mock_pid_map:
177
+ if pid == 99995:
178
+ # simulate a bug reported in #95
179
+ raise FileNotFoundError("/proc/99995/stat")
180
+ else:
181
+ # for a process that does not exist, NoSuchProcess is the
182
+ # type of exceptions supposed to be raised by psutil
183
+ raise psutil.NoSuchProcess(pid=pid)
184
+ username, cmdline, cpuutil, memutil = mock_pid_map[pid]
185
+ p: Any = mock(strict=True) # psutil.Process
186
+ p.username = lambda: username
187
+ p.cmdline = lambda: [cmdline]
188
+ p.cpu_percent = lambda: cpuutil
189
+ p.memory_percent = lambda: memutil
190
+ p.pid = pid
191
+ return p
192
+
193
+ when(psutil).Process(...)\
194
+ .thenAnswer(_MockedProcess)
195
+ when(psutil).virtual_memory()\
196
+ .thenReturn(mock_memory_t(total=8589934592, used=0))
197
+
198
+
199
+ MOCK_EXPECTED_OUTPUT_DEFAULT = os.linesep.join("""\
200
+ [0] GeForce GTX TITAN 0 | 80°C, 76 % | 8000 / 12287 MB | user1(4000M) user2(4000M)
201
+ [1] GeForce GTX TITAN 1 | 36°C, 0 % | 9000 / 12189 MB | user1(3000M) user3(6000M)
202
+ [2] GeForce RTX 2 | 71°C, ?? % | 0 / 12189 MB | (Not Supported)
203
+ """.splitlines()) # noqa: E501
204
+
205
+ MOCK_EXPECTED_OUTPUT_FULL = os.linesep.join("""\
206
+ [0] GeForce GTX TITAN 0 | 80°C, 16 %, 76 % (E: 88 % D: 67 %), 125 / 250 W | 8000 / 12287 MB | user1:python/48448(4000M) user2:python/153223(4000M)
207
+ [1] GeForce GTX TITAN 1 | 36°C, 53 %, 0 % (E: 0 % D: 0 %), ?? / 250 W | 9000 / 12189 MB | user1:torch/192453(3000M) user3:caffe/194826(6000M)
208
+ [2] GeForce RTX 2 | 71°C, 100 %, ?? % (E: ?? % D: ?? %), 250 / ?? W | 0 / 12189 MB | (Not Supported)
209
+ """.splitlines()) # noqa: E501
210
+
211
+ MOCK_EXPECTED_OUTPUT_FULL_PROCESS = os.linesep.join("""\
212
+ [0] GeForce GTX TITAN 0 | 80°C, 16 %, 76 % (E: 88 % D: 67 %), 125 / 250 W | 8000 / 12287 MB | user1:python/48448(4000M) user2:python/153223(4000M)
213
+ ├─ 48448 ( 85%, 257MB): python
214
+ └─ 153223 ( 15%, 0B): python
215
+ [1] GeForce GTX TITAN 1 | 36°C, 53 %, 0 % (E: 0 % D: 0 %), ?? / 250 W | 9000 / 12189 MB | user1:torch/192453(3000M) user3:caffe/194826(6000M)
216
+ ├─ 192453 ( 123%, 59MB): torch
217
+ └─ 194826 ( 0%, 1025MB): caffe
218
+ [2] GeForce RTX 2 | 71°C, 100 %, ?? % (E: ?? % D: ?? %), 250 / ?? W | 0 / 12189 MB | (Not Supported)
219
+ """.splitlines()) # noqa: E501
220
+
221
+ MOCK_EXPECTED_OUTPUT_NO_PROCESSES = os.linesep.join("""\
222
+ [0] GeForce GTX TITAN 0 | 80°C, 76 % | 8000 / 12287 MB
223
+ [1] GeForce GTX TITAN 1 | 36°C, 0 % | 9000 / 12189 MB
224
+ [2] GeForce RTX 2 | 71°C, ?? % | 0 / 12189 MB
225
+ """.splitlines()) # noqa: E501
226
+
227
+ # -----------------------------------------------------------------------------
228
+
229
+
230
+ @pytest.fixture
231
+ def scenario_basic():
232
+ _configure_mock()
233
+
234
+
235
+ @pytest.fixture
236
+ def scenario_nonexistent_pid():
237
+ _configure_mock(_scenario_nonexistent_pid=True)
238
+
239
+
240
+ @pytest.fixture
241
+ def scenario_failing_one_gpu(request: pytest.FixtureRequest):
242
+ # request.param should be either NVMLError_Unknown or NVMLError_GpuIsLost
243
+ _configure_mock(_scenario_failing_one_gpu=request.param)
244
+ return dict(expected_message={
245
+ pynvml.NVMLError_GpuIsLost: 'GPU is lost',
246
+ pynvml.NVMLError_Unknown: 'Unknown Error',
247
+ }[request.param])
248
+
249
+
250
+ @pytest.fixture
251
+ def nvidia_driver_version(request: pytest.FixtureRequest):
252
+ """See NvidiaDriverMock."""
253
+
254
+ nvidia_mock: NvidiaDriverMock = request.param
255
+ nvidia_mock(pynvml)
256
+
257
+ if nvidia_mock.name.startswith('430'):
258
+ # AssertionError: gpustat will print (Not Supported) in this case
259
+ request.node.add_marker(pytest.mark.xfail(
260
+ reason="nvmlDeviceGetComputeRunningProcesses_v2 does not exist"))
261
+
262
+ yield nvidia_mock
263
+
264
+
265
+ class NvidiaDriverMock:
266
+ """Simulate the behavior of nvml's low-level functions according to a
267
+ specific nvidia driver versions, with backward compatibility in concern.
268
+ In all the scenarios, gpustat should work well with a compatible version
269
+ of pynvml installed.
270
+
271
+ For what has changed on the nvidia driver side (a non-exhaustive list), see
272
+ https://github.com/NVIDIA/nvidia-settings/blame/main/src/nvml.h
273
+ https://github.com/NVIDIA/nvidia-settings/blame/main/src/libXNVCtrlAttributes/NvCtrlAttributesPrivate.h
274
+
275
+ Noteworthy changes of nvml driviers:
276
+ 450.66: nvmlDeviceGetComputeRunningProcesses_v2
277
+ 510.39.01: nvmlDeviceGetComputeRunningProcesses_v3 (_v2 removed)
278
+ nvmlDeviceGetMemoryInfo_v2
279
+
280
+ Relevant github issues:
281
+ #107: nvmlDeviceGetComputeRunningProcesses_v2 added
282
+ #141: nvmlDeviceGetMemoryInfo (v1) broken for 510.39.01+
283
+ """
284
+ INSTANCES = []
285
+
286
+ def __init__(self, name, **kwargs):
287
+ self.name = name
288
+ self.feat = kwargs
289
+
290
+ def __call__(self, N):
291
+ self.mock_processes(N)
292
+ self.mock_memoryinfo(N)
293
+
294
+ def mock_processes(self, N):
295
+ when(N).nvmlDeviceGetComputeRunningProcesses(...).thenCallOriginalImplementation()
296
+ when(N).nvmlDeviceGetGraphicsRunningProcesses(...).thenCallOriginalImplementation()
297
+ when(N).nvmlSystemGetDriverVersion().thenReturn(self.name)
298
+
299
+ def process_t(pid, usedGpuMemory):
300
+ return pynvml.c_nvmlProcessInfo_t(
301
+ pid=ctypes.c_uint(pid),
302
+ usedGpuMemory=ctypes.c_ulonglong(usedGpuMemory),
303
+ )
304
+
305
+ # more low-level mocking for
306
+ # nvmlDeviceGetComputeRunningProcesses_{v2, v3} & c_nvmlProcessInfo_t
307
+ def _nvmlDeviceGetComputeRunningProcesses_v2(handle, c_count, c_procs):
308
+ # handle: SimpleNamespace (see _configure_mock)
309
+ if c_count._obj.value == 0:
310
+ return pynvml.NVML_ERROR_INSUFFICIENT_SIZE
311
+ else:
312
+ c_count._obj.value = 2
313
+ if handle.index == 0:
314
+ c = process_t(pid=48448, usedGpuMemory=4000*MB); c_procs[0] = c
315
+ c = process_t(pid=153223, usedGpuMemory=4000*MB); c_procs[1] = c
316
+ elif handle.index == 1:
317
+ c = process_t(pid=192453, usedGpuMemory=3000*MB); c_procs[0] = c
318
+ c = process_t(pid=194826, usedGpuMemory=6000*MB); c_procs[1] = c
319
+ else:
320
+ return pynvml.NVML_ERROR_NOT_SUPPORTED
321
+ return pynvml.NVML_SUCCESS
322
+
323
+ def _nvmlDeviceGetGraphicsRunningProcesses_v2(handle, c_count, c_procs):
324
+ if c_count._obj.value == 0:
325
+ return pynvml.NVML_ERROR_INSUFFICIENT_SIZE
326
+ else:
327
+ if handle.index == 0:
328
+ c_count._obj.value = 1
329
+ c = process_t(pid=48448, usedGpuMemory=4000*MB); c_procs[0] = c
330
+ elif handle.index == 1:
331
+ c_count._obj.value = 0
332
+ else:
333
+ return pynvml.NVML_ERROR_NOT_SUPPORTED
334
+ return pynvml.NVML_SUCCESS
335
+
336
+ # Note: N._nvmlGetFunctionPointer might have been monkey-patched,
337
+ # so this mock should decorate the underlying, unwrapped raw function,
338
+ # NOT a monkey-patched version of pynvml._nvmlGetFunctionPointer.
339
+ for v in [1, 2, 3]:
340
+ _v = f'_v{v}' if v != 1 else '' # backward compatible v3 -> v2
341
+ stub = when2(pynvml_monkeypatch.original_nvmlGetFunctionPointer,
342
+ f'nvmlDeviceGetComputeRunningProcesses{_v}')
343
+ if v <= self.nvmlDeviceGetComputeRunningProcesses_v:
344
+ stub.thenReturn(_nvmlDeviceGetComputeRunningProcesses_v2)
345
+ else:
346
+ stub.thenRaise(pynvml.NVMLError(pynvml.NVML_ERROR_FUNCTION_NOT_FOUND))
347
+
348
+ stub = when2(pynvml_monkeypatch.original_nvmlGetFunctionPointer,
349
+ f'nvmlDeviceGetGraphicsRunningProcesses{_v}')
350
+ if v <= self.nvmlDeviceGetComputeRunningProcesses_v:
351
+ stub.thenReturn(_nvmlDeviceGetGraphicsRunningProcesses_v2)
352
+ else:
353
+ stub.thenRaise(pynvml.NVMLError(pynvml.NVML_ERROR_FUNCTION_NOT_FOUND))
354
+
355
+ def mock_memoryinfo(self, N):
356
+ nvmlMemory_v2 = 0x02000028
357
+ if self.nvmlDeviceGetMemoryInfo_v == 1:
358
+ mock_memory_t = namedtuple(
359
+ "c_nvmlMemory_t",
360
+ ['total', 'used'],
361
+ )
362
+ elif self.nvmlDeviceGetMemoryInfo_v == 2:
363
+ mock_memory_t = namedtuple(
364
+ "c_nvmlMemory_v2_t",
365
+ ['version', 'total', 'reserved', 'free', 'used'],
366
+ )
367
+ mock_memory_t.__new__.__defaults__ = (nvmlMemory_v2, 0, 0, 0, 0)
368
+ else:
369
+ raise NotImplementedError
370
+
371
+ # simulates drivers >= 510.39, where memoryinfo v2 is introduced
372
+ if self.nvmlDeviceGetMemoryInfo_v == 2:
373
+ for handle in mock_gpu_handles:
374
+ # a correct API requires version=... parameter
375
+ # this assumes nvidia driver is also recent enough.
376
+ when(pynvml_monkeypatch, strict=False)\
377
+ .original_nvmlDeviceGetMemoryInfo(handle, version=nvmlMemory_v2)\
378
+ .thenReturn({
379
+ 0: mock_memory_t(total=12883853312, used=8000*MB),
380
+ 1: mock_memory_t(total=12781551616, used=9000*MB),
381
+ 2: mock_memory_t(total=12781551616, used=0),
382
+ }[handle.index])
383
+ # simulate #141: without the v2 parameter, gives wrong result
384
+ when(pynvml_monkeypatch)\
385
+ .original_nvmlDeviceGetMemoryInfo(handle)\
386
+ .thenReturn({
387
+ 0: mock_memory_t(total=12883853312, used=8099*MB),
388
+ 1: mock_memory_t(total=12781551616, used=9099*MB),
389
+ 2: mock_memory_t(total=12781551616, used=99*MB),
390
+ }[handle.index])
391
+
392
+ else: # old drivers < 510.39
393
+ for handle in mock_gpu_handles:
394
+ # when pynvml>=11.510, v2 API can be called but can't be used
395
+ when(N, strict=False)\
396
+ .nvmlDeviceGetMemoryInfo(handle, version=ANY())\
397
+ .thenRaise(N.NVMLError_FunctionNotFound)
398
+ # The v1 API will give a correct result for the v1 API
399
+ when(N).nvmlDeviceGetMemoryInfo(handle)\
400
+ .thenReturn({
401
+ 0: mock_memory_t(total=12883853312, used=8000*MB),
402
+ 1: mock_memory_t(total=12781551616, used=9000*MB),
403
+ 2: mock_memory_t(total=12781551616, used=0),
404
+ }[handle.index])
405
+
406
+ def __getattr__(self, k):
407
+ return self.feat[k]
408
+
409
+ @property
410
+ def __name__(self):
411
+ return self.name
412
+
413
+ def __repr__(self):
414
+ return self.__name__
415
+
416
+
417
+ NvidiaDriverMock.INSTANCES = [
418
+ NvidiaDriverMock('430.xx.xx',
419
+ nvmlDeviceGetComputeRunningProcesses_v=1,
420
+ nvmlDeviceGetMemoryInfo_v=1,
421
+ ),
422
+ NvidiaDriverMock('450.66',
423
+ nvmlDeviceGetComputeRunningProcesses_v=2,
424
+ nvmlDeviceGetMemoryInfo_v=1,
425
+ ),
426
+ NvidiaDriverMock('510.39.01',
427
+ nvmlDeviceGetComputeRunningProcesses_v=3,
428
+ nvmlDeviceGetMemoryInfo_v=2,
429
+ ),
430
+ ]
431
+
432
+
433
+ # -----------------------------------------------------------------------------
434
+
435
+
436
+ class TestGPUStat(object):
437
+ """A pytest class suite for gpustat."""
438
+
439
+ def setup_method(self):
440
+ print("")
441
+ self.maxDiff = 4096
442
+
443
+ def teardown_method(self):
444
+ unstub()
445
+
446
+ @staticmethod
447
+ def capture_output(*args):
448
+ f = StringIO()
449
+ import contextlib
450
+
451
+ with contextlib.redirect_stdout(f): # requires python 3.4+
452
+ try:
453
+ gpustat.main(*args)
454
+ except SystemExit as e:
455
+ if e.code != 0:
456
+ raise AssertionError(
457
+ "Argparse failed (see above error message)")
458
+ return f.getvalue()
459
+
460
+ # -----------------------------------------------------------------------
461
+
462
+ @pytest.mark.parametrize("nvidia_driver_version",
463
+ NvidiaDriverMock.INSTANCES, indirect=True)
464
+ def test_new_query_mocked_basic(self, scenario_basic, nvidia_driver_version):
465
+ """A basic functionality test, in a case where everything is normal."""
466
+
467
+ gpustats = gpustat.new_query()
468
+ fp = StringIO()
469
+ gpustats.print_formatted(
470
+ fp=fp, no_color=False, show_user=True,
471
+ show_cmd=True, show_full_cmd=True, show_pid=True,
472
+ show_fan_speed=True, show_codec="enc,dec", show_power=True,
473
+ )
474
+
475
+ result = fp.getvalue()
476
+ print(result)
477
+
478
+ unescaped = remove_ansi_codes(result)
479
+ # remove first line (header)
480
+ unescaped = os.linesep.join(unescaped.splitlines()[1:])
481
+
482
+ assert unescaped == MOCK_EXPECTED_OUTPUT_FULL_PROCESS
483
+
484
+ # verify gpustat results (not exhaustive yet)
485
+ assert gpustats.driver_version == nvidia_driver_version.name
486
+ g: gpustat.GPUStat = gpustats.gpus[0]
487
+ assert g.memory_used == 8000
488
+ assert g.power_draw == 125
489
+ assert g.utilization == 76
490
+ assert g.processes and g.processes[0]['pid'] == 48448
491
+
492
+ def test_new_query_mocked_nonexistent_pid(self, scenario_nonexistent_pid):
493
+ """
494
+ Test a case where nvidia query returns non-existent pids (see #16, #18)
495
+ for GPU index 2.
496
+ """
497
+ fp = StringIO()
498
+
499
+ gpustats = gpustat.new_query()
500
+ gpustats.print_formatted(fp=fp)
501
+
502
+ ret = fp.getvalue()
503
+ print(ret)
504
+
505
+ # gpu 2: should ignore process id
506
+ line = remove_ansi_codes(ret).split('\n')[3]
507
+ assert '[2] GeForce RTX 2' in line, str(line)
508
+ assert '99999' not in line
509
+ assert '(Not Supported)' not in line
510
+
511
+ @pytest.mark.parametrize("scenario_failing_one_gpu", [
512
+ pynvml.NVMLError_GpuIsLost,
513
+ pynvml.NVMLError_Unknown,
514
+ ], indirect=True)
515
+ def test_new_query_mocked_failing_one_gpu(self, scenario_failing_one_gpu):
516
+ """Test a case where one GPU is failing (see #125)."""
517
+ fp = StringIO()
518
+ gpustats = gpustat.new_query()
519
+ gpustats.print_formatted(fp=fp, show_header=False)
520
+ ret = fp.getvalue()
521
+ print(ret)
522
+
523
+ lines = remove_ansi_codes(ret).split('\n')
524
+ message = scenario_failing_one_gpu['expected_message']
525
+
526
+ # gpu 2: failing due to unknown error
527
+ line = lines[2]
528
+ assert '[2] ((' + message + '))' in line, str(line)
529
+ assert '99999' not in line
530
+ assert '?°C, ? %' in line, str(line)
531
+ assert '? / ? MB' in line, str(line)
532
+
533
+ # other gpus should be displayed normally
534
+ assert '[0] GeForce GTX TITAN 0' in lines[0]
535
+ assert '[1] GeForce GTX TITAN 1' in lines[1]
536
+
537
+ def test_attributes_and_items(self, scenario_basic):
538
+ """Test whether each property of `GPUStat` instance is well-defined."""
539
+
540
+ g = gpustat.new_query()[1] # includes N/A
541
+ print("(keys) : %s" % str(g.keys()))
542
+ print(g)
543
+
544
+ assert g['name'] == g.entry['name']
545
+ assert g['uuid'] == g.uuid
546
+
547
+ with pytest.raises(KeyError):
548
+ g['unknown_key']
549
+
550
+ print("uuid : %s" % g.uuid)
551
+ print("name : %s" % g.name)
552
+ print("memory : used %d total %d avail %d" % (
553
+ g.memory_used, g.memory_total, g.memory_available))
554
+ print("temperature : %d" % (g.temperature))
555
+ print("utilization : %s" % (g.utilization))
556
+ print("utilization_enc : %s" % (g.utilization_enc))
557
+ print("utilization_dec : %s" % (g.utilization_dec))
558
+
559
+ def test_main(self, scenario_basic):
560
+ """Test whether gpustat.main() works well.
561
+ The behavior is mocked exactly as in test_new_query_mocked().
562
+ """
563
+ sys.argv = ['gpustat']
564
+ gpustat.main()
565
+
566
+ def test_args_commandline(self, scenario_basic):
567
+ """Tests the end gpustat CLI."""
568
+ capture_output = self.capture_output
569
+
570
+ def _remove_ansi_codes_and_header_line(s):
571
+ unescaped = remove_ansi_codes(s)
572
+ # remove first line (header)
573
+ unescaped = os.linesep.join(unescaped.splitlines()[1:])
574
+ return unescaped
575
+
576
+ s = capture_output('gpustat', )
577
+ assert _remove_ansi_codes_and_header_line(s) == MOCK_EXPECTED_OUTPUT_DEFAULT
578
+
579
+ s = capture_output('gpustat', '--version')
580
+ assert s.startswith('gpustat ')
581
+ print(s)
582
+
583
+ s = capture_output('gpustat', '--no-header')
584
+ assert "[0]" in s.splitlines()[0]
585
+
586
+ s = capture_output('gpustat', '-a') # --show-all
587
+ assert _remove_ansi_codes_and_header_line(s) == MOCK_EXPECTED_OUTPUT_FULL
588
+
589
+ s = capture_output('gpustat', '--color')
590
+ assert '\x0f' not in s, "Extra \\x0f found (see issue #32)"
591
+ assert _remove_ansi_codes_and_header_line(s) == MOCK_EXPECTED_OUTPUT_DEFAULT
592
+
593
+ s = capture_output('gpustat', '--no-color')
594
+ unescaped = remove_ansi_codes(s)
595
+ assert s == unescaped # should have no ansi code
596
+ assert _remove_ansi_codes_and_header_line(s) == MOCK_EXPECTED_OUTPUT_DEFAULT
597
+
598
+ s = capture_output('gpustat', '--no-processes')
599
+ assert _remove_ansi_codes_and_header_line(s) == MOCK_EXPECTED_OUTPUT_NO_PROCESSES
600
+
601
+ s = capture_output('gpustat', '--id', '1,2')
602
+ assert _remove_ansi_codes_and_header_line(s) == \
603
+ os.linesep.join(MOCK_EXPECTED_OUTPUT_DEFAULT.splitlines()[1:3])
604
+
605
+ def test_args_commandline_width(self, scenario_basic):
606
+ capture_output = self.capture_output
607
+
608
+ # see MOCK_EXPECTED_OUTPUT_DEFAULT
609
+ assert len("GeForce GTX TITAN 0") == 19
610
+
611
+ s = capture_output('gpustat', '--gpuname-width', '25')
612
+ print("- Should have width=25")
613
+ print(s)
614
+ assert 'GeForce GTX TITAN 0 |' in remove_ansi_codes(s)
615
+ assert 'GeForce RTX 2 |' in remove_ansi_codes(s)
616
+ # ^012345
617
+ # 19
618
+
619
+ # See #47 (since v1.0)
620
+ print("- Should have width=10 (with truncation)")
621
+ s = capture_output('gpustat', '--gpuname-width', '10')
622
+ print(s)
623
+ assert '…X TITAN 0 |' in remove_ansi_codes(s)
624
+ assert '…rce RTX 2 |' in remove_ansi_codes(s)
625
+ # 1234567890
626
+
627
+ print("- Should have width=1 (too short)")
628
+ s = capture_output('gpustat', '--gpuname-width', '1')
629
+ print(s)
630
+ assert '… |' in remove_ansi_codes(s)
631
+
632
+ print("- Should have width=0: no name displayed.")
633
+ s = capture_output('gpustat', '--gpuname-width', '0')
634
+ print(s)
635
+ assert '[0] 80°C' in remove_ansi_codes(s)
636
+
637
+ print("- Invalid inputs")
638
+ with pytest.raises(AssertionError, match="Argparse failed"):
639
+ s = capture_output('gpustat', '--gpuname-width', '-1')
640
+ with pytest.raises(AssertionError, match="Argparse failed"):
641
+ s = capture_output('gpustat', '--gpuname-width', 'None')
642
+
643
+ def test_args_commandline_showoptions(self, scenario_basic):
644
+ """Tests gpustat CLI with a variety of --show-xxx options. """
645
+
646
+ capture_output = self.capture_output
647
+ print('')
648
+
649
+ TEST_OPTS = []
650
+ TEST_OPTS += ['-a', '-c', '-u', '-p', '-e', '-P', '-f']
651
+ TEST_OPTS += [('-e', ''), ('-P', '')]
652
+ TEST_OPTS += [('-e', 'enc,dec'), '-Plimit,draw']
653
+ TEST_OPTS += ['-cup', '-cpu', '-cufP'] # 'cpuePf'
654
+
655
+ for opt in TEST_OPTS:
656
+ if isinstance(opt, str):
657
+ opt = [opt]
658
+
659
+ print('\x1b[30m\x1b[43m', # black_on_yellow
660
+ '$ gpustat ' + ' '.join(shlex.quote(o) for o in opt),
661
+ '\x1b(B\x1b[m', sep='')
662
+ s = capture_output('gpustat', *opt)
663
+
664
+ # TODO: Validate output without hardcoding expected outputs
665
+ print(s)
666
+
667
+ # Finally, unknown args
668
+ with pytest.raises(AssertionError):
669
+ capture_output('gpustat', '--unrecognized-args-in-test')
670
+
671
+ @pytest.mark.skipif(sys.platform == 'win32', reason="Do not run on Windows")
672
+ def test_no_TERM(self, scenario_basic, monkeypatch):
673
+ """--color should work well even when executed without TERM,
674
+ e.g. ssh localhost gpustat --color"""
675
+ monkeypatch.setenv("TERM", "")
676
+
677
+ s = self.capture_output('gpustat', '--color', '--no-header').rstrip()
678
+ print(s)
679
+ assert remove_ansi_codes(s) == MOCK_EXPECTED_OUTPUT_DEFAULT, \
680
+ "wrong gpustat output"
681
+
682
+ assert '\x1b[36m' in s, "should contain cyan color code"
683
+ assert '\x0f' not in s, "Extra \\x0f found (see issue #32)"
684
+
685
+ def test_json_mocked(self, scenario_basic):
686
+ gpustats = gpustat.new_query()
687
+
688
+ fp = StringIO()
689
+ gpustats.print_json(fp=fp)
690
+
691
+ import json
692
+ j = json.loads(fp.getvalue())
693
+
694
+ from pprint import pprint
695
+ pprint(j)
696
+
697
+ assert j['driver_version'] == '415.27.mock'
698
+ assert j['hostname']
699
+ assert j['gpus']
700
+
701
+
702
+ if __name__ == '__main__':
703
+ pytest.main()
vllm/lib/python3.10/site-packages/gpustat/util.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Miscellaneous Utilities. """
2
+
3
+ import collections
4
+ import os.path
5
+ import sys
6
+ import traceback
7
+ from typing import Callable, Tuple, Type, TypeVar, Union
8
+
9
+ T = TypeVar('T')
10
+
11
+
12
+ def bytes2human(in_bytes):
13
+ '''Convert bytes (int) to a human-readable string.'''
14
+ suffixes = ('B', 'KB', 'MB', 'GB', 'TB', 'PB')
15
+ suffix = 0
16
+ result = int(in_bytes)
17
+ while result > 9999 and suffix < len(suffixes):
18
+ result = result >> 10
19
+ suffix += 1
20
+
21
+ if suffix >= len(suffixes):
22
+ suffix -= 1
23
+ return "%d%s" % (result, suffixes[suffix])
24
+
25
+
26
+ def prettify_commandline(cmdline, color_command='', color_text=''):
27
+ '''
28
+ Prettify and colorize a full command-line (given as list of strings),
29
+ where command (basename) is highlighted in a different color.
30
+ '''
31
+ # cmdline: Iterable[str]
32
+ if isinstance(cmdline, str):
33
+ return cmdline
34
+ assert cmdline
35
+
36
+ command_p, command_b = os.path.split(cmdline[0])
37
+ s = color_text + os.path.join(command_p,
38
+ color_command + command_b + color_text)
39
+
40
+ if len(cmdline) > 1:
41
+ s += ' '
42
+ s += ' '.join(cmdline[1:])
43
+ return s
44
+
45
+
46
+ def shorten_left(text, width, placeholder="…"):
47
+ # text: str
48
+ if width is None:
49
+ return text
50
+ if text is None or len(text) <= width:
51
+ return text
52
+ if width < 0:
53
+ raise ValueError("width must be non-negative.")
54
+ if width == 0:
55
+ return ""
56
+
57
+ if width == len(placeholder):
58
+ return placeholder
59
+ elif width - len(placeholder) < 0:
60
+ return placeholder[:width]
61
+ # raise ValueError("width is smaller than the length of placeholder.")
62
+ return placeholder + text[-(width - len(placeholder)):]
63
+
64
+
65
+ def safecall(fn: Callable[[], T],
66
+ *,
67
+ exc_types: Union[Type, Tuple[Type, ...]] = Exception,
68
+ error_value: T) -> T:
69
+ """A protected call that suppress certain types of exceptions."""
70
+ try:
71
+ return fn()
72
+ except exc_types: # pylint: disable=broad-except
73
+ return error_value
74
+
75
+
76
+ class DebugHelper:
77
+
78
+ def __init__(self):
79
+ self._reports = []
80
+
81
+ def add_exception(self, column, e=None):
82
+ msg = "> An error while retrieving `{column}`: {e}".format(
83
+ column=column, e=str(e))
84
+ self._reports.append((msg, e))
85
+
86
+ def _write(self, msg):
87
+ sys.stderr.write(msg)
88
+ sys.stderr.write('\n')
89
+
90
+ def report_summary(self, concise=True):
91
+ _seen_messages = collections.defaultdict(int)
92
+ for msg, e in self._reports:
93
+ if msg not in _seen_messages or not concise:
94
+ self._write(msg)
95
+ self._write(''.join(
96
+ traceback.format_exception(None, e, e.__traceback__)))
97
+ _seen_messages[msg] += 1
98
+
99
+ if concise:
100
+ for msg, value in _seen_messages.items():
101
+ self._write("{msg} -> Total {value} occurrences.".format(
102
+ msg=msg, value=value))
103
+ self._write('')
vllm/lib/python3.10/site-packages/gpustat/util_test.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import pytest
3
+
4
+ from gpustat import util
5
+
6
+
7
+ def test_safecall():
8
+
9
+ def _success():
10
+ return 42
11
+
12
+ def _error():
13
+ raise FileNotFoundError("oops")
14
+
15
+ assert util.safecall(_success, error_value=None) == 42
16
+ assert util.safecall(_error, error_value=-1) == -1
17
+
18
+ with pytest.raises(FileNotFoundError):
19
+ # not catched because exc_types does not match
20
+ assert util.safecall(_error, exc_types=ValueError, error_value=-1)
21
+
22
+ assert util.safecall(_error, error_value=-1,
23
+ exc_types=FileNotFoundError) == -1
24
+ assert util.safecall(_error, error_value=-1,
25
+ exc_types=(FileNotFoundError, OSError)) == -1
26
+
27
+
28
+ if __name__ == '__main__':
29
+ sys.exit(pytest.main(["-s", "-v"] + sys.argv))
vllm/lib/python3.10/site-packages/httptools-0.6.4.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
vllm/lib/python3.10/site-packages/httptools-0.6.4.dist-info/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License
2
+
3
+ Copyright (c) 2015 MagicStack Inc. http://magic.io
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
vllm/lib/python3.10/site-packages/httptools-0.6.4.dist-info/METADATA ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: httptools
3
+ Version: 0.6.4
4
+ Summary: A collection of framework independent HTTP protocol utils.
5
+ Home-page: https://github.com/MagicStack/httptools
6
+ Author: Yury Selivanov
7
+ Author-email: yury@magic.io
8
+ License: MIT
9
+ Platform: macOS
10
+ Platform: POSIX
11
+ Platform: Windows
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Operating System :: POSIX
16
+ Classifier: Operating System :: MacOS :: MacOS X
17
+ Classifier: Environment :: Web Environment
18
+ Classifier: Development Status :: 5 - Production/Stable
19
+ Requires-Python: >=3.8.0
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Provides-Extra: test
23
+ Requires-Dist: Cython>=0.29.24; extra == "test"
24
+
25
+ ![Tests](https://github.com/MagicStack/httptools/workflows/Tests/badge.svg)
26
+
27
+ httptools is a Python binding for the nodejs HTTP parser.
28
+
29
+ The package is available on PyPI: `pip install httptools`.
30
+
31
+
32
+ # APIs
33
+
34
+ httptools contains two classes `httptools.HttpRequestParser`,
35
+ `httptools.HttpResponseParser` (fulfilled through
36
+ [llhttp](https://github.com/nodejs/llhttp)) and a function for
37
+ parsing URLs `httptools.parse_url` (through
38
+ [http-parse](https://github.com/nodejs/http-parser) for now).
39
+ See unittests for examples.
40
+
41
+
42
+ ```python
43
+
44
+ class HttpRequestParser:
45
+
46
+ def __init__(self, protocol):
47
+ """HttpRequestParser
48
+
49
+ protocol -- a Python object with the following methods
50
+ (all optional):
51
+
52
+ - on_message_begin()
53
+ - on_url(url: bytes)
54
+ - on_header(name: bytes, value: bytes)
55
+ - on_headers_complete()
56
+ - on_body(body: bytes)
57
+ - on_message_complete()
58
+ - on_chunk_header()
59
+ - on_chunk_complete()
60
+ - on_status(status: bytes)
61
+ """
62
+
63
+ def get_http_version(self) -> str:
64
+ """Return an HTTP protocol version."""
65
+
66
+ def should_keep_alive(self) -> bool:
67
+ """Return ``True`` if keep-alive mode is preferred."""
68
+
69
+ def should_upgrade(self) -> bool:
70
+ """Return ``True`` if the parsed request is a valid Upgrade request.
71
+ The method exposes a flag set just before on_headers_complete.
72
+ Calling this method earlier will only yield `False`.
73
+ """
74
+
75
+ def feed_data(self, data: bytes):
76
+ """Feed data to the parser.
77
+
78
+ Will eventually trigger callbacks on the ``protocol``
79
+ object.
80
+
81
+ On HTTP upgrade, this method will raise an
82
+ ``HttpParserUpgrade`` exception, with its sole argument
83
+ set to the offset of the non-HTTP data in ``data``.
84
+ """
85
+
86
+ def get_method(self) -> bytes:
87
+ """Return HTTP request method (GET, HEAD, etc)"""
88
+
89
+
90
+ class HttpResponseParser:
91
+
92
+ """Has all methods except ``get_method()`` that
93
+ HttpRequestParser has."""
94
+
95
+ def get_status_code(self) -> int:
96
+ """Return the status code of the HTTP response"""
97
+
98
+
99
+ def parse_url(url: bytes):
100
+ """Parse URL strings into a structured Python object.
101
+
102
+ Returns an instance of ``httptools.URL`` class with the
103
+ following attributes:
104
+
105
+ - schema: bytes
106
+ - host: bytes
107
+ - port: int
108
+ - path: bytes
109
+ - query: bytes
110
+ - fragment: bytes
111
+ - userinfo: bytes
112
+ """
113
+ ```
114
+
115
+
116
+ # Development
117
+
118
+ 1. Clone this repository with
119
+ `git clone --recursive git@github.com:MagicStack/httptools.git`
120
+
121
+ 2. Create a virtual environment with Python 3:
122
+ `python3 -m venv envname`
123
+
124
+ 3. Activate the environment with `source envname/bin/activate`
125
+
126
+ 4. Install development requirements with `pip install -e .[test]`
127
+
128
+ 5. Run `make` and `make test`.
129
+
130
+
131
+ # License
132
+
133
+ MIT.
vllm/lib/python3.10/site-packages/httptools-0.6.4.dist-info/RECORD ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ httptools-0.6.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ httptools-0.6.4.dist-info/LICENSE,sha256=9Fc-fLdnZ0X7W402-lSKqT45HPtoct2s1lEwxF6mqS0,1093
3
+ httptools-0.6.4.dist-info/METADATA,sha256=U4VRvayKRJbdHp18Fagk4_L7RvIQJ4anhwtwS64rO9A,3583
4
+ httptools-0.6.4.dist-info/RECORD,,
5
+ httptools-0.6.4.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ httptools-0.6.4.dist-info/WHEEL,sha256=2JiXcU0-Qfy9gwog3WAIw4e5slUs9ReZ9xqrxqqbExM,224
7
+ httptools-0.6.4.dist-info/top_level.txt,sha256=APjJKTbZcj0OQ4fdgf2eTCk82nK1n2BFXOD7ky41MPY,10
8
+ httptools/__init__.py,sha256=plt3MIbueJdco9Dy7zoH3ksLNeyirqWagat5rwRmAjo,147
9
+ httptools/__pycache__/__init__.cpython-310.pyc,,
10
+ httptools/__pycache__/_version.cpython-310.pyc,,
11
+ httptools/_version.py,sha256=ASqOB8fLS7jwZsM551Lc49WxYPyjteqnz1iDWmka-KA,575
12
+ httptools/parser/__init__.py,sha256=fWyconPEHZlJojzRwmBKSn4C85OGXmKEwiEcdjHqXO8,166
13
+ httptools/parser/__pycache__/__init__.cpython-310.pyc,,
14
+ httptools/parser/__pycache__/errors.cpython-310.pyc,,
15
+ httptools/parser/cparser.pxd,sha256=4qBxnma83Vz86Z9sOZRxjqYj20A-aLSWVGXZgTVLJqE,4977
16
+ httptools/parser/errors.py,sha256=ZVrtN1smPIb_opQ2Ud3uCbGlNLMlECYM2-6S7r5LnHs,566
17
+ httptools/parser/parser.cpython-310-x86_64-linux-gnu.so,sha256=gUJVhgrfY6kfy5lOsa1_8lIFPtbRLot_obcQUnrfRuk,1028176
18
+ httptools/parser/parser.pyx,sha256=x0BUY9EzHNKCDaw-U8bkZ1MaKGtrOQ8iVCm1IuOtEQI,15140
19
+ httptools/parser/python.pxd,sha256=zWCdGZh34fyQNt3BUHIUjPqY8a5sodRUkfdABxqYHgQ,138
20
+ httptools/parser/url_cparser.pxd,sha256=X5dDI8A7T0l5HL_Czt0mTs0l_d2lXnUDHx1TN8LeiCM,779
21
+ httptools/parser/url_parser.cpython-310-x86_64-linux-gnu.so,sha256=rG1YT8DYa7kfGmsTITKzLi1H-ZJShJEkJWXnziUo0JU,426712
22
+ httptools/parser/url_parser.pyx,sha256=ZJVUZqrIDdhzVodA7tTtoFb570av-SczIyh2oAZXKzM,3758
vllm/lib/python3.10/site-packages/httptools-0.6.4.dist-info/REQUESTED ADDED
File without changes
vllm/lib/python3.10/site-packages/httptools-0.6.4.dist-info/WHEEL ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.1.0)
3
+ Root-Is-Purelib: false
4
+ Tag: cp310-cp310-manylinux_2_5_x86_64
5
+ Tag: cp310-cp310-manylinux1_x86_64
6
+ Tag: cp310-cp310-manylinux_2_17_x86_64
7
+ Tag: cp310-cp310-manylinux2014_x86_64
8
+
vllm/lib/python3.10/site-packages/httptools-0.6.4.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ httptools
vllm/lib/python3.10/site-packages/inflection/__init__.py ADDED
@@ -0,0 +1,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ inflection
4
+ ~~~~~~~~~~~~
5
+
6
+ A port of Ruby on Rails' inflector to Python.
7
+
8
+ :copyright: (c) 2012-2020 by Janne Vanhala
9
+
10
+ :license: MIT, see LICENSE for more details.
11
+ """
12
+ import re
13
+ import unicodedata
14
+
15
+ __version__ = '0.5.1'
16
+
17
+ PLURALS = [
18
+ (r"(?i)(quiz)$", r'\1zes'),
19
+ (r"(?i)^(oxen)$", r'\1'),
20
+ (r"(?i)^(ox)$", r'\1en'),
21
+ (r"(?i)(m|l)ice$", r'\1ice'),
22
+ (r"(?i)(m|l)ouse$", r'\1ice'),
23
+ (r"(?i)(passer)s?by$", r'\1sby'),
24
+ (r"(?i)(matr|vert|ind)(?:ix|ex)$", r'\1ices'),
25
+ (r"(?i)(x|ch|ss|sh)$", r'\1es'),
26
+ (r"(?i)([^aeiouy]|qu)y$", r'\1ies'),
27
+ (r"(?i)(hive)$", r'\1s'),
28
+ (r"(?i)([lr])f$", r'\1ves'),
29
+ (r"(?i)([^f])fe$", r'\1ves'),
30
+ (r"(?i)sis$", 'ses'),
31
+ (r"(?i)([ti])a$", r'\1a'),
32
+ (r"(?i)([ti])um$", r'\1a'),
33
+ (r"(?i)(buffal|potat|tomat)o$", r'\1oes'),
34
+ (r"(?i)(bu)s$", r'\1ses'),
35
+ (r"(?i)(alias|status)$", r'\1es'),
36
+ (r"(?i)(octop|vir)i$", r'\1i'),
37
+ (r"(?i)(octop|vir)us$", r'\1i'),
38
+ (r"(?i)^(ax|test)is$", r'\1es'),
39
+ (r"(?i)s$", 's'),
40
+ (r"$", 's'),
41
+ ]
42
+
43
+ SINGULARS = [
44
+ (r"(?i)(database)s$", r'\1'),
45
+ (r"(?i)(quiz)zes$", r'\1'),
46
+ (r"(?i)(matr)ices$", r'\1ix'),
47
+ (r"(?i)(vert|ind)ices$", r'\1ex'),
48
+ (r"(?i)(passer)sby$", r'\1by'),
49
+ (r"(?i)^(ox)en", r'\1'),
50
+ (r"(?i)(alias|status)(es)?$", r'\1'),
51
+ (r"(?i)(octop|vir)(us|i)$", r'\1us'),
52
+ (r"(?i)^(a)x[ie]s$", r'\1xis'),
53
+ (r"(?i)(cris|test)(is|es)$", r'\1is'),
54
+ (r"(?i)(shoe)s$", r'\1'),
55
+ (r"(?i)(o)es$", r'\1'),
56
+ (r"(?i)(bus)(es)?$", r'\1'),
57
+ (r"(?i)(m|l)ice$", r'\1ouse'),
58
+ (r"(?i)(x|ch|ss|sh)es$", r'\1'),
59
+ (r"(?i)(m)ovies$", r'\1ovie'),
60
+ (r"(?i)(s)eries$", r'\1eries'),
61
+ (r"(?i)([^aeiouy]|qu)ies$", r'\1y'),
62
+ (r"(?i)([lr])ves$", r'\1f'),
63
+ (r"(?i)(tive)s$", r'\1'),
64
+ (r"(?i)(hive)s$", r'\1'),
65
+ (r"(?i)([^f])ves$", r'\1fe'),
66
+ (r"(?i)(t)he(sis|ses)$", r"\1hesis"),
67
+ (r"(?i)(s)ynop(sis|ses)$", r"\1ynopsis"),
68
+ (r"(?i)(p)rogno(sis|ses)$", r"\1rognosis"),
69
+ (r"(?i)(p)arenthe(sis|ses)$", r"\1arenthesis"),
70
+ (r"(?i)(d)iagno(sis|ses)$", r"\1iagnosis"),
71
+ (r"(?i)(b)a(sis|ses)$", r"\1asis"),
72
+ (r"(?i)(a)naly(sis|ses)$", r"\1nalysis"),
73
+ (r"(?i)([ti])a$", r'\1um'),
74
+ (r"(?i)(n)ews$", r'\1ews'),
75
+ (r"(?i)(ss)$", r'\1'),
76
+ (r"(?i)s$", ''),
77
+ ]
78
+
79
+ UNCOUNTABLES = {
80
+ 'equipment',
81
+ 'fish',
82
+ 'information',
83
+ 'jeans',
84
+ 'money',
85
+ 'rice',
86
+ 'series',
87
+ 'sheep',
88
+ 'species'}
89
+
90
+
91
+ def _irregular(singular: str, plural: str) -> None:
92
+ """
93
+ A convenience function to add appropriate rules to plurals and singular
94
+ for irregular words.
95
+
96
+ :param singular: irregular word in singular form
97
+ :param plural: irregular word in plural form
98
+ """
99
+ def caseinsensitive(string: str) -> str:
100
+ return ''.join('[' + char + char.upper() + ']' for char in string)
101
+
102
+ if singular[0].upper() == plural[0].upper():
103
+ PLURALS.insert(0, (
104
+ r"(?i)({}){}$".format(singular[0], singular[1:]),
105
+ r'\1' + plural[1:]
106
+ ))
107
+ PLURALS.insert(0, (
108
+ r"(?i)({}){}$".format(plural[0], plural[1:]),
109
+ r'\1' + plural[1:]
110
+ ))
111
+ SINGULARS.insert(0, (
112
+ r"(?i)({}){}$".format(plural[0], plural[1:]),
113
+ r'\1' + singular[1:]
114
+ ))
115
+ else:
116
+ PLURALS.insert(0, (
117
+ r"{}{}$".format(singular[0].upper(),
118
+ caseinsensitive(singular[1:])),
119
+ plural[0].upper() + plural[1:]
120
+ ))
121
+ PLURALS.insert(0, (
122
+ r"{}{}$".format(singular[0].lower(),
123
+ caseinsensitive(singular[1:])),
124
+ plural[0].lower() + plural[1:]
125
+ ))
126
+ PLURALS.insert(0, (
127
+ r"{}{}$".format(plural[0].upper(), caseinsensitive(plural[1:])),
128
+ plural[0].upper() + plural[1:]
129
+ ))
130
+ PLURALS.insert(0, (
131
+ r"{}{}$".format(plural[0].lower(), caseinsensitive(plural[1:])),
132
+ plural[0].lower() + plural[1:]
133
+ ))
134
+ SINGULARS.insert(0, (
135
+ r"{}{}$".format(plural[0].upper(), caseinsensitive(plural[1:])),
136
+ singular[0].upper() + singular[1:]
137
+ ))
138
+ SINGULARS.insert(0, (
139
+ r"{}{}$".format(plural[0].lower(), caseinsensitive(plural[1:])),
140
+ singular[0].lower() + singular[1:]
141
+ ))
142
+
143
+
144
+ def camelize(string: str, uppercase_first_letter: bool = True) -> str:
145
+ """
146
+ Convert strings to CamelCase.
147
+
148
+ Examples::
149
+
150
+ >>> camelize("device_type")
151
+ 'DeviceType'
152
+ >>> camelize("device_type", False)
153
+ 'deviceType'
154
+
155
+ :func:`camelize` can be thought of as a inverse of :func:`underscore`,
156
+ although there are some cases where that does not hold::
157
+
158
+ >>> camelize(underscore("IOError"))
159
+ 'IoError'
160
+
161
+ :param uppercase_first_letter: if set to `True` :func:`camelize` converts
162
+ strings to UpperCamelCase. If set to `False` :func:`camelize` produces
163
+ lowerCamelCase. Defaults to `True`.
164
+ """
165
+ if uppercase_first_letter:
166
+ return re.sub(r"(?:^|_)(.)", lambda m: m.group(1).upper(), string)
167
+ else:
168
+ return string[0].lower() + camelize(string)[1:]
169
+
170
+
171
+ def dasherize(word: str) -> str:
172
+ """Replace underscores with dashes in the string.
173
+
174
+ Example::
175
+
176
+ >>> dasherize("puni_puni")
177
+ 'puni-puni'
178
+
179
+ """
180
+ return word.replace('_', '-')
181
+
182
+
183
+ def humanize(word: str) -> str:
184
+ """
185
+ Capitalize the first word and turn underscores into spaces and strip a
186
+ trailing ``"_id"``, if any. Like :func:`titleize`, this is meant for
187
+ creating pretty output.
188
+
189
+ Examples::
190
+
191
+ >>> humanize("employee_salary")
192
+ 'Employee salary'
193
+ >>> humanize("author_id")
194
+ 'Author'
195
+
196
+ """
197
+ word = re.sub(r"_id$", "", word)
198
+ word = word.replace('_', ' ')
199
+ word = re.sub(r"(?i)([a-z\d]*)", lambda m: m.group(1).lower(), word)
200
+ word = re.sub(r"^\w", lambda m: m.group(0).upper(), word)
201
+ return word
202
+
203
+
204
+ def ordinal(number: int) -> str:
205
+ """
206
+ Return the suffix that should be added to a number to denote the position
207
+ in an ordered sequence such as 1st, 2nd, 3rd, 4th.
208
+
209
+ Examples::
210
+
211
+ >>> ordinal(1)
212
+ 'st'
213
+ >>> ordinal(2)
214
+ 'nd'
215
+ >>> ordinal(1002)
216
+ 'nd'
217
+ >>> ordinal(1003)
218
+ 'rd'
219
+ >>> ordinal(-11)
220
+ 'th'
221
+ >>> ordinal(-1021)
222
+ 'st'
223
+
224
+ """
225
+ number = abs(int(number))
226
+ if number % 100 in (11, 12, 13):
227
+ return "th"
228
+ else:
229
+ return {
230
+ 1: "st",
231
+ 2: "nd",
232
+ 3: "rd",
233
+ }.get(number % 10, "th")
234
+
235
+
236
+ def ordinalize(number: int) -> str:
237
+ """
238
+ Turn a number into an ordinal string used to denote the position in an
239
+ ordered sequence such as 1st, 2nd, 3rd, 4th.
240
+
241
+ Examples::
242
+
243
+ >>> ordinalize(1)
244
+ '1st'
245
+ >>> ordinalize(2)
246
+ '2nd'
247
+ >>> ordinalize(1002)
248
+ '1002nd'
249
+ >>> ordinalize(1003)
250
+ '1003rd'
251
+ >>> ordinalize(-11)
252
+ '-11th'
253
+ >>> ordinalize(-1021)
254
+ '-1021st'
255
+
256
+ """
257
+ return "{}{}".format(number, ordinal(number))
258
+
259
+
260
+ def parameterize(string: str, separator: str = '-') -> str:
261
+ """
262
+ Replace special characters in a string so that it may be used as part of a
263
+ 'pretty' URL.
264
+
265
+ Example::
266
+
267
+ >>> parameterize(u"Donald E. Knuth")
268
+ 'donald-e-knuth'
269
+
270
+ """
271
+ string = transliterate(string)
272
+ # Turn unwanted chars into the separator
273
+ string = re.sub(r"(?i)[^a-z0-9\-_]+", separator, string)
274
+ if separator:
275
+ re_sep = re.escape(separator)
276
+ # No more than one of the separator in a row.
277
+ string = re.sub(r'%s{2,}' % re_sep, separator, string)
278
+ # Remove leading/trailing separator.
279
+ string = re.sub(r"(?i)^{sep}|{sep}$".format(sep=re_sep), '', string)
280
+
281
+ return string.lower()
282
+
283
+
284
+ def pluralize(word: str) -> str:
285
+ """
286
+ Return the plural form of a word.
287
+
288
+ Examples::
289
+
290
+ >>> pluralize("posts")
291
+ 'posts'
292
+ >>> pluralize("octopus")
293
+ 'octopi'
294
+ >>> pluralize("sheep")
295
+ 'sheep'
296
+ >>> pluralize("CamelOctopus")
297
+ 'CamelOctopi'
298
+
299
+ """
300
+ if not word or word.lower() in UNCOUNTABLES:
301
+ return word
302
+ else:
303
+ for rule, replacement in PLURALS:
304
+ if re.search(rule, word):
305
+ return re.sub(rule, replacement, word)
306
+ return word
307
+
308
+
309
+ def singularize(word: str) -> str:
310
+ """
311
+ Return the singular form of a word, the reverse of :func:`pluralize`.
312
+
313
+ Examples::
314
+
315
+ >>> singularize("posts")
316
+ 'post'
317
+ >>> singularize("octopi")
318
+ 'octopus'
319
+ >>> singularize("sheep")
320
+ 'sheep'
321
+ >>> singularize("word")
322
+ 'word'
323
+ >>> singularize("CamelOctopi")
324
+ 'CamelOctopus'
325
+
326
+ """
327
+ for inflection in UNCOUNTABLES:
328
+ if re.search(r'(?i)\b(%s)\Z' % inflection, word):
329
+ return word
330
+
331
+ for rule, replacement in SINGULARS:
332
+ if re.search(rule, word):
333
+ return re.sub(rule, replacement, word)
334
+ return word
335
+
336
+
337
+ def tableize(word: str) -> str:
338
+ """
339
+ Create the name of a table like Rails does for models to table names. This
340
+ method uses the :func:`pluralize` method on the last word in the string.
341
+
342
+ Examples::
343
+
344
+ >>> tableize('RawScaledScorer')
345
+ 'raw_scaled_scorers'
346
+ >>> tableize('egg_and_ham')
347
+ 'egg_and_hams'
348
+ >>> tableize('fancyCategory')
349
+ 'fancy_categories'
350
+ """
351
+ return pluralize(underscore(word))
352
+
353
+
354
+ def titleize(word: str) -> str:
355
+ """
356
+ Capitalize all the words and replace some characters in the string to
357
+ create a nicer looking title. :func:`titleize` is meant for creating pretty
358
+ output.
359
+
360
+ Examples::
361
+
362
+ >>> titleize("man from the boondocks")
363
+ 'Man From The Boondocks'
364
+ >>> titleize("x-men: the last stand")
365
+ 'X Men: The Last Stand'
366
+ >>> titleize("TheManWithoutAPast")
367
+ 'The Man Without A Past'
368
+ >>> titleize("raiders_of_the_lost_ark")
369
+ 'Raiders Of The Lost Ark'
370
+
371
+ """
372
+ return re.sub(
373
+ r"\b('?\w)",
374
+ lambda match: match.group(1).capitalize(),
375
+ humanize(underscore(word)).title()
376
+ )
377
+
378
+
379
+ def transliterate(string: str) -> str:
380
+ """
381
+ Replace non-ASCII characters with an ASCII approximation. If no
382
+ approximation exists, the non-ASCII character is ignored. The string must
383
+ be ``unicode``.
384
+
385
+ Examples::
386
+
387
+ >>> transliterate('älämölö')
388
+ 'alamolo'
389
+ >>> transliterate('Ærøskøbing')
390
+ 'rskbing'
391
+
392
+ """
393
+ normalized = unicodedata.normalize('NFKD', string)
394
+ return normalized.encode('ascii', 'ignore').decode('ascii')
395
+
396
+
397
+ def underscore(word: str) -> str:
398
+ """
399
+ Make an underscored, lowercase form from the expression in the string.
400
+
401
+ Example::
402
+
403
+ >>> underscore("DeviceType")
404
+ 'device_type'
405
+
406
+ As a rule of thumb you can think of :func:`underscore` as the inverse of
407
+ :func:`camelize`, though there are cases where that does not hold::
408
+
409
+ >>> camelize(underscore("IOError"))
410
+ 'IoError'
411
+
412
+ """
413
+ word = re.sub(r"([A-Z]+)([A-Z][a-z])", r'\1_\2', word)
414
+ word = re.sub(r"([a-z\d])([A-Z])", r'\1_\2', word)
415
+ word = word.replace("-", "_")
416
+ return word.lower()
417
+
418
+
419
+ _irregular('person', 'people')
420
+ _irregular('man', 'men')
421
+ _irregular('human', 'humans')
422
+ _irregular('child', 'children')
423
+ _irregular('sex', 'sexes')
424
+ _irregular('move', 'moves')
425
+ _irregular('cow', 'kine')
426
+ _irregular('zombie', 'zombies')
vllm/lib/python3.10/site-packages/inflection/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (10.9 kB). View file