LCZZZZ commited on
Commit
e34b94f
·
verified ·
1 Parent(s): 2f3f2b8

Upload MemGen code and data

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +5 -0
  2. .gitignore +17 -0
  3. .venv/.gitignore +1 -0
  4. .venv/.lock +0 -0
  5. .venv/CACHEDIR.TAG +1 -0
  6. .venv/bin/activate +130 -0
  7. .venv/bin/activate.bat +71 -0
  8. .venv/bin/activate.csh +76 -0
  9. .venv/bin/activate.fish +124 -0
  10. .venv/bin/activate.nu +102 -0
  11. .venv/bin/activate.ps1 +82 -0
  12. .venv/bin/activate_this.py +59 -0
  13. .venv/bin/deactivate.bat +39 -0
  14. .venv/bin/nvisel +10 -0
  15. .venv/bin/nvitop +10 -0
  16. .venv/bin/pydoc.bat +22 -0
  17. .venv/bin/python +3 -0
  18. .venv/bin/python3 +3 -0
  19. .venv/bin/python3.10 +3 -0
  20. .venv/lib/python3.10/site-packages/_virtualenv.pth +3 -0
  21. .venv/lib/python3.10/site-packages/_virtualenv.py +101 -0
  22. .venv/lib/python3.10/site-packages/example.py +169 -0
  23. .venv/lib/python3.10/site-packages/nvidia_ml_py-13.580.82.dist-info/INSTALLER +1 -0
  24. .venv/lib/python3.10/site-packages/nvidia_ml_py-13.580.82.dist-info/METADATA +284 -0
  25. .venv/lib/python3.10/site-packages/nvidia_ml_py-13.580.82.dist-info/RECORD +8 -0
  26. .venv/lib/python3.10/site-packages/nvidia_ml_py-13.580.82.dist-info/REQUESTED +0 -0
  27. .venv/lib/python3.10/site-packages/nvidia_ml_py-13.580.82.dist-info/WHEEL +5 -0
  28. .venv/lib/python3.10/site-packages/nvidia_ml_py-13.580.82.dist-info/top_level.txt +2 -0
  29. .venv/lib/python3.10/site-packages/nvitop-1.5.3.dist-info/INSTALLER +1 -0
  30. .venv/lib/python3.10/site-packages/nvitop-1.5.3.dist-info/METADATA +1563 -0
  31. .venv/lib/python3.10/site-packages/nvitop-1.5.3.dist-info/RECORD +60 -0
  32. .venv/lib/python3.10/site-packages/nvitop-1.5.3.dist-info/REQUESTED +0 -0
  33. .venv/lib/python3.10/site-packages/nvitop-1.5.3.dist-info/WHEEL +5 -0
  34. .venv/lib/python3.10/site-packages/nvitop-1.5.3.dist-info/entry_points.txt +3 -0
  35. .venv/lib/python3.10/site-packages/nvitop-1.5.3.dist-info/licenses/COPYING +674 -0
  36. .venv/lib/python3.10/site-packages/nvitop-1.5.3.dist-info/licenses/LICENSE +202 -0
  37. .venv/lib/python3.10/site-packages/nvitop-1.5.3.dist-info/top_level.txt +1 -0
  38. .venv/lib/python3.10/site-packages/nvitop/__init__.py +60 -0
  39. .venv/lib/python3.10/site-packages/nvitop/__main__.py +12 -0
  40. .venv/lib/python3.10/site-packages/nvitop/api/__init__.py +114 -0
  41. .venv/lib/python3.10/site-packages/nvitop/api/caching.py +279 -0
  42. .venv/lib/python3.10/site-packages/nvitop/api/collector.py +912 -0
  43. .venv/lib/python3.10/site-packages/nvitop/api/device.py +0 -0
  44. .venv/lib/python3.10/site-packages/nvitop/api/host.py +149 -0
  45. .venv/lib/python3.10/site-packages/nvitop/api/libcuda.py +747 -0
  46. .venv/lib/python3.10/site-packages/nvitop/api/libcudart.py +735 -0
  47. .venv/lib/python3.10/site-packages/nvitop/api/libnvml.py +1020 -0
  48. .venv/lib/python3.10/site-packages/nvitop/api/process.py +1056 -0
  49. .venv/lib/python3.10/site-packages/nvitop/api/termcolor.py +284 -0
  50. .venv/lib/python3.10/site-packages/nvitop/api/utils.py +799 -0
.gitattributes CHANGED
@@ -33,3 +33,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ .venv/bin/python filter=lfs diff=lfs merge=lfs -text
37
+ .venv/bin/python3 filter=lfs diff=lfs merge=lfs -text
38
+ .venv/bin/python3.10 filter=lfs diff=lfs merge=lfs -text
39
+ .venv/lib/python3.10/site-packages/psutil/_psutil_linux.abi3.so filter=lfs diff=lfs merge=lfs -text
40
+ assets/memgen.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ test_output/
2
+ # data/*
3
+ **.pyc
4
+ **.pyo
5
+ **.pyd
6
+ **.pyw
7
+ **.pyz
8
+ **.pywz
9
+ **.pyzw
10
+ **.pyzwz
11
+ **.pyzwzw
12
+ **.pyzwzwzw
13
+
14
+ model/
15
+ results/
16
+ dataset/
17
+ .env
.venv/.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ *
.venv/.lock ADDED
File without changes
.venv/CACHEDIR.TAG ADDED
@@ -0,0 +1 @@
 
 
1
+ Signature: 8a477f597d28d172789f06886806bc55
.venv/bin/activate ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ # This file must be used with "source bin/activate" *from bash*
23
+ # you cannot run it directly
24
+
25
+ if ! [ -z "${SCRIPT_PATH+_}" ] ; then
26
+ _OLD_SCRIPT_PATH="$SCRIPT_PATH"
27
+ fi
28
+
29
+ # Get script path (only used if environment is relocatable).
30
+ if [ -n "${BASH_VERSION:+x}" ] ; then
31
+ SCRIPT_PATH="${BASH_SOURCE[0]}"
32
+ if [ "$SCRIPT_PATH" = "$0" ]; then
33
+ # Only bash has a reasonably robust check for source'dness.
34
+ echo "You must source this script: \$ source $0" >&2
35
+ exit 33
36
+ fi
37
+ elif [ -n "${ZSH_VERSION:+x}" ] ; then
38
+ SCRIPT_PATH="${(%):-%x}"
39
+ elif [ -n "${KSH_VERSION:+x}" ] ; then
40
+ SCRIPT_PATH="${.sh.file}"
41
+ fi
42
+
43
+ deactivate () {
44
+ unset -f pydoc >/dev/null 2>&1 || true
45
+
46
+ # reset old environment variables
47
+ # ! [ -z ${VAR+_} ] returns true if VAR is declared at all
48
+ if ! [ -z "${_OLD_VIRTUAL_PATH:+_}" ] ; then
49
+ PATH="$_OLD_VIRTUAL_PATH"
50
+ export PATH
51
+ unset _OLD_VIRTUAL_PATH
52
+ fi
53
+ if ! [ -z "${_OLD_VIRTUAL_PYTHONHOME+_}" ] ; then
54
+ PYTHONHOME="$_OLD_VIRTUAL_PYTHONHOME"
55
+ export PYTHONHOME
56
+ unset _OLD_VIRTUAL_PYTHONHOME
57
+ fi
58
+
59
+ # The hash command must be called to get it to forget past
60
+ # commands. Without forgetting past commands the $PATH changes
61
+ # we made may not be respected
62
+ hash -r 2>/dev/null
63
+
64
+ if ! [ -z "${_OLD_VIRTUAL_PS1+_}" ] ; then
65
+ PS1="$_OLD_VIRTUAL_PS1"
66
+ export PS1
67
+ unset _OLD_VIRTUAL_PS1
68
+ fi
69
+
70
+ unset VIRTUAL_ENV
71
+ unset VIRTUAL_ENV_PROMPT
72
+ if [ ! "${1-}" = "nondestructive" ] ; then
73
+ # Self destruct!
74
+ unset -f deactivate
75
+ fi
76
+ }
77
+
78
+ # unset irrelevant variables
79
+ deactivate nondestructive
80
+
81
+ VIRTUAL_ENV='/root/CVPR/MemGen/.venv'
82
+ if ([ "$OSTYPE" = "cygwin" ] || [ "$OSTYPE" = "msys" ]) && $(command -v cygpath &> /dev/null) ; then
83
+ VIRTUAL_ENV=$(cygpath -u "$VIRTUAL_ENV")
84
+ fi
85
+ export VIRTUAL_ENV
86
+
87
+ # Unset the `SCRIPT_PATH` variable, now that the `VIRTUAL_ENV` variable
88
+ # has been set. This is important for relocatable environments.
89
+ if ! [ -z "${_OLD_SCRIPT_PATH+_}" ] ; then
90
+ SCRIPT_PATH="$_OLD_SCRIPT_PATH"
91
+ export SCRIPT_PATH
92
+ unset _OLD_SCRIPT_PATH
93
+ else
94
+ unset SCRIPT_PATH
95
+ fi
96
+
97
+ _OLD_VIRTUAL_PATH="$PATH"
98
+ PATH="$VIRTUAL_ENV/bin:$PATH"
99
+ export PATH
100
+
101
+ if [ "xMemGen" != x ] ; then
102
+ VIRTUAL_ENV_PROMPT="MemGen"
103
+ else
104
+ VIRTUAL_ENV_PROMPT=$(basename "$VIRTUAL_ENV")
105
+ fi
106
+ export VIRTUAL_ENV_PROMPT
107
+
108
+ # unset PYTHONHOME if set
109
+ if ! [ -z "${PYTHONHOME+_}" ] ; then
110
+ _OLD_VIRTUAL_PYTHONHOME="$PYTHONHOME"
111
+ unset PYTHONHOME
112
+ fi
113
+
114
+ if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT-}" ] ; then
115
+ _OLD_VIRTUAL_PS1="${PS1-}"
116
+ PS1="(${VIRTUAL_ENV_PROMPT}) ${PS1-}"
117
+ export PS1
118
+ fi
119
+
120
+ # Make sure to unalias pydoc if it's already there
121
+ alias pydoc 2>/dev/null >/dev/null && unalias pydoc || true
122
+
123
+ pydoc () {
124
+ python -m pydoc "$@"
125
+ }
126
+
127
+ # The hash command must be called to get it to forget past
128
+ # commands. Without forgetting past commands the $PATH changes
129
+ # we made may not be respected
130
+ hash -r 2>/dev/null || true
.venv/bin/activate.bat ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @REM Copyright (c) 2020-202x The virtualenv developers
2
+ @REM
3
+ @REM Permission is hereby granted, free of charge, to any person obtaining
4
+ @REM a copy of this software and associated documentation files (the
5
+ @REM "Software"), to deal in the Software without restriction, including
6
+ @REM without limitation the rights to use, copy, modify, merge, publish,
7
+ @REM distribute, sublicense, and/or sell copies of the Software, and to
8
+ @REM permit persons to whom the Software is furnished to do so, subject to
9
+ @REM the following conditions:
10
+ @REM
11
+ @REM The above copyright notice and this permission notice shall be
12
+ @REM included in all copies or substantial portions of the Software.
13
+ @REM
14
+ @REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ @REM EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ @REM MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ @REM NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ @REM LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ @REM OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ @REM WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ @REM This file is UTF-8 encoded, so we need to update the current code page while executing it
23
+ @for /f "tokens=2 delims=:." %%a in ('"%SystemRoot%\System32\chcp.com"') do @set _OLD_CODEPAGE=%%a
24
+
25
+ @if defined _OLD_CODEPAGE (
26
+ "%SystemRoot%\System32\chcp.com" 65001 > nul
27
+ )
28
+
29
+ @for %%i in ("/root/CVPR/MemGen/.venv") do @set "VIRTUAL_ENV=%%~fi"
30
+
31
+ @set "VIRTUAL_ENV_PROMPT=MemGen"
32
+ @if NOT DEFINED VIRTUAL_ENV_PROMPT (
33
+ @for %%d in ("%VIRTUAL_ENV%") do @set "VIRTUAL_ENV_PROMPT=%%~nxd"
34
+ )
35
+
36
+ @if defined _OLD_VIRTUAL_PROMPT (
37
+ @set "PROMPT=%_OLD_VIRTUAL_PROMPT%"
38
+ ) else (
39
+ @if not defined PROMPT (
40
+ @set "PROMPT=$P$G"
41
+ )
42
+ @if not defined VIRTUAL_ENV_DISABLE_PROMPT (
43
+ @set "_OLD_VIRTUAL_PROMPT=%PROMPT%"
44
+ )
45
+ )
46
+ @if not defined VIRTUAL_ENV_DISABLE_PROMPT (
47
+ @set "PROMPT=(%VIRTUAL_ENV_PROMPT%) %PROMPT%"
48
+ )
49
+
50
+ @REM Don't use () to avoid problems with them in %PATH%
51
+ @if defined _OLD_VIRTUAL_PYTHONHOME @goto ENDIFVHOME
52
+ @set "_OLD_VIRTUAL_PYTHONHOME=%PYTHONHOME%"
53
+ :ENDIFVHOME
54
+
55
+ @set PYTHONHOME=
56
+
57
+ @REM if defined _OLD_VIRTUAL_PATH (
58
+ @if not defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH1
59
+ @set "PATH=%_OLD_VIRTUAL_PATH%"
60
+ :ENDIFVPATH1
61
+ @REM ) else (
62
+ @if defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH2
63
+ @set "_OLD_VIRTUAL_PATH=%PATH%"
64
+ :ENDIFVPATH2
65
+
66
+ @set "PATH=%VIRTUAL_ENV%\bin;%PATH%"
67
+
68
+ @if defined _OLD_CODEPAGE (
69
+ "%SystemRoot%\System32\chcp.com" %_OLD_CODEPAGE% > nul
70
+ @set _OLD_CODEPAGE=
71
+ )
.venv/bin/activate.csh ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ # This file must be used with "source bin/activate.csh" *from csh*.
23
+ # You cannot run it directly.
24
+ # Created by Davide Di Blasi <[email protected]>.
25
+
26
+ set newline='\
27
+ '
28
+
29
+ alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH:q" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT:q" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; unsetenv VIRTUAL_ENV_PROMPT; test "\!:*" != "nondestructive" && unalias deactivate && unalias pydoc'
30
+
31
+ # Unset irrelevant variables.
32
+ deactivate nondestructive
33
+
34
+ setenv VIRTUAL_ENV '/root/CVPR/MemGen/.venv'
35
+
36
+ set _OLD_VIRTUAL_PATH="$PATH:q"
37
+ setenv PATH "$VIRTUAL_ENV:q/bin:$PATH:q"
38
+
39
+
40
+
41
+ if ('MemGen' != "") then
42
+ setenv VIRTUAL_ENV_PROMPT 'MemGen'
43
+ else
44
+ setenv VIRTUAL_ENV_PROMPT "$VIRTUAL_ENV:t:q"
45
+ endif
46
+
47
+ if ( $?VIRTUAL_ENV_DISABLE_PROMPT ) then
48
+ if ( $VIRTUAL_ENV_DISABLE_PROMPT == "" ) then
49
+ set do_prompt = "1"
50
+ else
51
+ set do_prompt = "0"
52
+ endif
53
+ else
54
+ set do_prompt = "1"
55
+ endif
56
+
57
+ if ( $do_prompt == "1" ) then
58
+ # Could be in a non-interactive environment,
59
+ # in which case, $prompt is undefined and we wouldn't
60
+ # care about the prompt anyway.
61
+ if ( $?prompt ) then
62
+ set _OLD_VIRTUAL_PROMPT="$prompt:q"
63
+ if ( "$prompt:q" =~ *"$newline:q"* ) then
64
+ :
65
+ else
66
+ set prompt = '('"$VIRTUAL_ENV_PROMPT:q"') '"$prompt:q"
67
+ endif
68
+ endif
69
+ endif
70
+
71
+ unset env_name
72
+ unset do_prompt
73
+
74
+ alias pydoc python -m pydoc
75
+
76
+ rehash
.venv/bin/activate.fish ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ # This file must be used using `source bin/activate.fish` *within a running fish ( http://fishshell.com ) session*.
23
+ # Do not run it directly.
24
+
25
+ function _bashify_path -d "Converts a fish path to something bash can recognize"
26
+ set fishy_path $argv
27
+ set bashy_path $fishy_path[1]
28
+ for path_part in $fishy_path[2..-1]
29
+ set bashy_path "$bashy_path:$path_part"
30
+ end
31
+ echo $bashy_path
32
+ end
33
+
34
+ function _fishify_path -d "Converts a bash path to something fish can recognize"
35
+ echo $argv | tr ':' '\n'
36
+ end
37
+
38
+ function deactivate -d 'Exit virtualenv mode and return to the normal environment.'
39
+ # reset old environment variables
40
+ if test -n "$_OLD_VIRTUAL_PATH"
41
+ # https://github.com/fish-shell/fish-shell/issues/436 altered PATH handling
42
+ if test (string sub -s 1 -l 1 $FISH_VERSION) -lt 3
43
+ set -gx PATH (_fishify_path "$_OLD_VIRTUAL_PATH")
44
+ else
45
+ set -gx PATH $_OLD_VIRTUAL_PATH
46
+ end
47
+ set -e _OLD_VIRTUAL_PATH
48
+ end
49
+
50
+ if test -n "$_OLD_VIRTUAL_PYTHONHOME"
51
+ set -gx PYTHONHOME "$_OLD_VIRTUAL_PYTHONHOME"
52
+ set -e _OLD_VIRTUAL_PYTHONHOME
53
+ end
54
+
55
+ if test -n "$_OLD_FISH_PROMPT_OVERRIDE"
56
+ and functions -q _old_fish_prompt
57
+ # Set an empty local `$fish_function_path` to allow the removal of `fish_prompt` using `functions -e`.
58
+ set -l fish_function_path
59
+
60
+ # Erase virtualenv's `fish_prompt` and restore the original.
61
+ functions -e fish_prompt
62
+ functions -c _old_fish_prompt fish_prompt
63
+ functions -e _old_fish_prompt
64
+ set -e _OLD_FISH_PROMPT_OVERRIDE
65
+ end
66
+
67
+ set -e VIRTUAL_ENV
68
+ set -e VIRTUAL_ENV_PROMPT
69
+
70
+ if test "$argv[1]" != 'nondestructive'
71
+ # Self-destruct!
72
+ functions -e pydoc
73
+ functions -e deactivate
74
+ functions -e _bashify_path
75
+ functions -e _fishify_path
76
+ end
77
+ end
78
+
79
+ # Unset irrelevant variables.
80
+ deactivate nondestructive
81
+
82
+ set -gx VIRTUAL_ENV '/root/CVPR/MemGen/.venv'
83
+
84
+ # https://github.com/fish-shell/fish-shell/issues/436 altered PATH handling
85
+ if test (string sub -s 1 -l 1 $FISH_VERSION) -lt 3
86
+ set -gx _OLD_VIRTUAL_PATH (_bashify_path $PATH)
87
+ else
88
+ set -gx _OLD_VIRTUAL_PATH $PATH
89
+ end
90
+ set -gx PATH "$VIRTUAL_ENV"'/bin' $PATH
91
+
92
+ # Prompt override provided?
93
+ # If not, just use the environment name.
94
+ if test -n 'MemGen'
95
+ set -gx VIRTUAL_ENV_PROMPT 'MemGen'
96
+ else
97
+ set -gx VIRTUAL_ENV_PROMPT (basename "$VIRTUAL_ENV")
98
+ end
99
+
100
+ # Unset `$PYTHONHOME` if set.
101
+ if set -q PYTHONHOME
102
+ set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME
103
+ set -e PYTHONHOME
104
+ end
105
+
106
+ function pydoc
107
+ python -m pydoc $argv
108
+ end
109
+
110
+ if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
111
+ # Copy the current `fish_prompt` function as `_old_fish_prompt`.
112
+ functions -c fish_prompt _old_fish_prompt
113
+
114
+ function fish_prompt
115
+ # Run the user's prompt first; it might depend on (pipe)status.
116
+ set -l prompt (_old_fish_prompt)
117
+
118
+ printf '(%s) ' $VIRTUAL_ENV_PROMPT
119
+
120
+ string join -- \n $prompt # handle multi-line prompts
121
+ end
122
+
123
+ set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"
124
+ end
.venv/bin/activate.nu ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ # virtualenv activation module:
23
+ # - Activate with `overlay use activate.nu`
24
+ # - Deactivate with `deactivate`, as usual
25
+ #
26
+ # To customize the overlay name, you can call `overlay use activate.nu as foo`, but then simply `deactivate` won't work
27
+ # because it is just an alias to hide the "activate" overlay. You'd need to call `overlay hide foo` manually.
28
+
29
+ module warning {
30
+ export-env {
31
+ const file = path self
32
+ error make -u {
33
+ msg: $"`($file | path basename)` is meant to be used with `overlay use`, not `source`"
34
+ }
35
+ }
36
+
37
+ }
38
+
39
+ use warning
40
+
41
+ export-env {
42
+
43
+ let nu_ver = (version | get version | split row '.' | take 2 | each { into int })
44
+ if $nu_ver.0 == 0 and $nu_ver.1 < 106 {
45
+ error make {
46
+ msg: 'virtualenv Nushell activation requires Nushell 0.106 or greater.'
47
+ }
48
+ }
49
+
50
+ def is-string [x] {
51
+ ($x | describe) == 'string'
52
+ }
53
+
54
+ def has-env [...names] {
55
+ $names | each {|n| $n in $env } | all {|i| $i }
56
+ }
57
+
58
+ def is-env-true [name: string] {
59
+ if (has-env $name) {
60
+ let val = ($env | get --optional $name)
61
+ if ($val | describe) == 'bool' {
62
+ $val
63
+ } else {
64
+ not ($val | is-empty)
65
+ }
66
+ } else {
67
+ false
68
+ }
69
+ }
70
+
71
+ let virtual_env = '/root/CVPR/MemGen/.venv'
72
+ let bin = 'bin'
73
+ let path_name = if (has-env 'Path') { 'Path' } else { 'PATH' }
74
+ let venv_path = ([$virtual_env $bin] | path join)
75
+ let new_path = ($env | get $path_name | prepend $venv_path)
76
+ let virtual_env_prompt = if ('MemGen' | is-empty) {
77
+ ($virtual_env | path basename)
78
+ } else {
79
+ 'MemGen'
80
+ }
81
+ let new_env = { $path_name: $new_path VIRTUAL_ENV: $virtual_env VIRTUAL_ENV_PROMPT: $virtual_env_prompt }
82
+ let old_prompt_command = if (has-env 'PROMPT_COMMAND') { $env.PROMPT_COMMAND } else { '' }
83
+ let new_env = if (is-env-true 'VIRTUAL_ENV_DISABLE_PROMPT') {
84
+ $new_env
85
+ } else {
86
+ let virtual_prefix = $'(char lparen)($virtual_env_prompt)(char rparen) '
87
+ let new_prompt = if (has-env 'PROMPT_COMMAND') {
88
+ if ('closure' in ($old_prompt_command | describe)) {
89
+ {|| $'($virtual_prefix)(do $old_prompt_command)' }
90
+ } else {
91
+ {|| $'($virtual_prefix)($old_prompt_command)' }
92
+ }
93
+ } else {
94
+ {|| $'($virtual_prefix)' }
95
+ }
96
+ $new_env | merge { PROMPT_COMMAND: $new_prompt VIRTUAL_PREFIX: $virtual_prefix }
97
+ }
98
+ load-env $new_env
99
+ }
100
+
101
+ export alias pydoc = python -m pydoc
102
+ export alias deactivate = overlay hide activate
.venv/bin/activate.ps1 ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ $script:THIS_PATH = $myinvocation.mycommand.path
23
+ $script:BASE_DIR = Split-Path (Resolve-Path "$THIS_PATH/..") -Parent
24
+
25
+ function global:deactivate([switch] $NonDestructive) {
26
+ if (Test-Path variable:_OLD_VIRTUAL_PATH) {
27
+ $env:PATH = $variable:_OLD_VIRTUAL_PATH
28
+ Remove-Variable "_OLD_VIRTUAL_PATH" -Scope global
29
+ }
30
+
31
+ if (Test-Path function:_old_virtual_prompt) {
32
+ $function:prompt = $function:_old_virtual_prompt
33
+ Remove-Item function:\_old_virtual_prompt
34
+ }
35
+
36
+ if ($env:VIRTUAL_ENV) {
37
+ Remove-Item env:VIRTUAL_ENV -ErrorAction SilentlyContinue
38
+ }
39
+
40
+ if ($env:VIRTUAL_ENV_PROMPT) {
41
+ Remove-Item env:VIRTUAL_ENV_PROMPT -ErrorAction SilentlyContinue
42
+ }
43
+
44
+ if (!$NonDestructive) {
45
+ # Self destruct!
46
+ Remove-Item function:deactivate
47
+ Remove-Item function:pydoc
48
+ }
49
+ }
50
+
51
+ function global:pydoc {
52
+ python -m pydoc $args
53
+ }
54
+
55
+ # unset irrelevant variables
56
+ deactivate -nondestructive
57
+
58
+ $VIRTUAL_ENV = $BASE_DIR
59
+ $env:VIRTUAL_ENV = $VIRTUAL_ENV
60
+
61
+ if ("MemGen" -ne "") {
62
+ $env:VIRTUAL_ENV_PROMPT = "MemGen"
63
+ }
64
+ else {
65
+ $env:VIRTUAL_ENV_PROMPT = $( Split-Path $env:VIRTUAL_ENV -Leaf )
66
+ }
67
+
68
+ New-Variable -Scope global -Name _OLD_VIRTUAL_PATH -Value $env:PATH
69
+
70
+ $env:PATH = "$env:VIRTUAL_ENV/bin:" + $env:PATH
71
+ if (!$env:VIRTUAL_ENV_DISABLE_PROMPT) {
72
+ function global:_old_virtual_prompt {
73
+ ""
74
+ }
75
+ $function:_old_virtual_prompt = $function:prompt
76
+
77
+ function global:prompt {
78
+ # Add the custom prefix to the existing prompt
79
+ $previous_prompt_value = & $function:_old_virtual_prompt
80
+ ("(" + $env:VIRTUAL_ENV_PROMPT + ") " + $previous_prompt_value)
81
+ }
82
+ }
.venv/bin/activate_this.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ """
23
+ Activate virtualenv for current interpreter:
24
+
25
+ import runpy
26
+ runpy.run_path(this_file)
27
+
28
+ This can be used when you must use an existing Python interpreter, not the virtualenv bin/python.
29
+ """ # noqa: D415
30
+
31
+ from __future__ import annotations
32
+
33
+ import os
34
+ import site
35
+ import sys
36
+
37
+ try:
38
+ abs_file = os.path.abspath(__file__)
39
+ except NameError as exc:
40
+ msg = "You must use import runpy; runpy.run_path(this_file)"
41
+ raise AssertionError(msg) from exc
42
+
43
+ bin_dir = os.path.dirname(abs_file)
44
+ base = bin_dir[: -len("bin") - 1] # strip away the bin part from the __file__, plus the path separator
45
+
46
+ # prepend bin to PATH (this file is inside the bin directory)
47
+ os.environ["PATH"] = os.pathsep.join([bin_dir, *os.environ.get("PATH", "").split(os.pathsep)])
48
+ os.environ["VIRTUAL_ENV"] = base # virtual env is right above bin directory
49
+ os.environ["VIRTUAL_ENV_PROMPT"] = "MemGen" or os.path.basename(base) # noqa: SIM222
50
+
51
+ # add the virtual environments libraries to the host python import mechanism
52
+ prev_length = len(sys.path)
53
+ for lib in "../lib/python3.10/site-packages".split(os.pathsep):
54
+ path = os.path.realpath(os.path.join(bin_dir, lib))
55
+ site.addsitedir(path)
56
+ sys.path[:] = sys.path[prev_length:] + sys.path[0:prev_length]
57
+
58
+ sys.real_prefix = sys.prefix
59
+ sys.prefix = base
.venv/bin/deactivate.bat ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @REM Copyright (c) 2020-202x The virtualenv developers
2
+ @REM
3
+ @REM Permission is hereby granted, free of charge, to any person obtaining
4
+ @REM a copy of this software and associated documentation files (the
5
+ @REM "Software"), to deal in the Software without restriction, including
6
+ @REM without limitation the rights to use, copy, modify, merge, publish,
7
+ @REM distribute, sublicense, and/or sell copies of the Software, and to
8
+ @REM permit persons to whom the Software is furnished to do so, subject to
9
+ @REM the following conditions:
10
+ @REM
11
+ @REM The above copyright notice and this permission notice shall be
12
+ @REM included in all copies or substantial portions of the Software.
13
+ @REM
14
+ @REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ @REM EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ @REM MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ @REM NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ @REM LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ @REM OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ @REM WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ @set VIRTUAL_ENV=
23
+ @set VIRTUAL_ENV_PROMPT=
24
+
25
+ @REM Don't use () to avoid problems with them in %PATH%
26
+ @if not defined _OLD_VIRTUAL_PROMPT @goto ENDIFVPROMPT
27
+ @set "PROMPT=%_OLD_VIRTUAL_PROMPT%"
28
+ @set _OLD_VIRTUAL_PROMPT=
29
+ :ENDIFVPROMPT
30
+
31
+ @if not defined _OLD_VIRTUAL_PYTHONHOME @goto ENDIFVHOME
32
+ @set "PYTHONHOME=%_OLD_VIRTUAL_PYTHONHOME%"
33
+ @set _OLD_VIRTUAL_PYTHONHOME=
34
+ :ENDIFVHOME
35
+
36
+ @if not defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH
37
+ @set "PATH=%_OLD_VIRTUAL_PATH%"
38
+ @set _OLD_VIRTUAL_PATH=
39
+ :ENDIFVPATH
.venv/bin/nvisel ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/root/CVPR/MemGen/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from nvitop.select import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/nvitop ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/root/CVPR/MemGen/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from nvitop.cli import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/pydoc.bat ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @REM Copyright (c) 2020-202x The virtualenv developers
2
+ @REM
3
+ @REM Permission is hereby granted, free of charge, to any person obtaining
4
+ @REM a copy of this software and associated documentation files (the
5
+ @REM "Software"), to deal in the Software without restriction, including
6
+ @REM without limitation the rights to use, copy, modify, merge, publish,
7
+ @REM distribute, sublicense, and/or sell copies of the Software, and to
8
+ @REM permit persons to whom the Software is furnished to do so, subject to
9
+ @REM the following conditions:
10
+ @REM
11
+ @REM The above copyright notice and this permission notice shall be
12
+ @REM included in all copies or substantial portions of the Software.
13
+ @REM
14
+ @REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ @REM EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ @REM MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ @REM NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ @REM LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ @REM OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ @REM WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ python.exe -m pydoc %*
.venv/bin/python ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dfcd193db9dc7318c3c0a6bd743aac2d92d5b2c1677b0c55031376b193327402
3
+ size 17250880
.venv/bin/python3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dfcd193db9dc7318c3c0a6bd743aac2d92d5b2c1677b0c55031376b193327402
3
+ size 17250880
.venv/bin/python3.10 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dfcd193db9dc7318c3c0a6bd743aac2d92d5b2c1677b0c55031376b193327402
3
+ size 17250880
.venv/lib/python3.10/site-packages/_virtualenv.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:69ac3d8f27e679c81b94ab30b3b56e9cd138219b1ba94a1fa3606d5a76a1433d
3
+ size 18
.venv/lib/python3.10/site-packages/_virtualenv.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Patches that are applied at runtime to the virtual environment."""
2
+
3
+ import os
4
+ import sys
5
+
6
+ VIRTUALENV_PATCH_FILE = os.path.join(__file__)
7
+
8
+
9
+ def patch_dist(dist):
10
+ """
11
+ Distutils allows user to configure some arguments via a configuration file:
12
+ https://docs.python.org/3.11/install/index.html#distutils-configuration-files.
13
+
14
+ Some of this arguments though don't make sense in context of the virtual environment files, let's fix them up.
15
+ """ # noqa: D205
16
+ # we cannot allow some install config as that would get packages installed outside of the virtual environment
17
+ old_parse_config_files = dist.Distribution.parse_config_files
18
+
19
+ def parse_config_files(self, *args, **kwargs):
20
+ result = old_parse_config_files(self, *args, **kwargs)
21
+ install = self.get_option_dict("install")
22
+
23
+ if "prefix" in install: # the prefix governs where to install the libraries
24
+ install["prefix"] = VIRTUALENV_PATCH_FILE, os.path.abspath(sys.prefix)
25
+ for base in ("purelib", "platlib", "headers", "scripts", "data"):
26
+ key = f"install_{base}"
27
+ if key in install: # do not allow global configs to hijack venv paths
28
+ install.pop(key, None)
29
+ return result
30
+
31
+ dist.Distribution.parse_config_files = parse_config_files
32
+
33
+
34
+ # Import hook that patches some modules to ignore configuration values that break package installation in case
35
+ # of virtual environments.
36
+ _DISTUTILS_PATCH = "distutils.dist", "setuptools.dist"
37
+ # https://docs.python.org/3/library/importlib.html#setting-up-an-importer
38
+
39
+
40
+ class _Finder:
41
+ """A meta path finder that allows patching the imported distutils modules."""
42
+
43
+ fullname = None
44
+
45
+ # lock[0] is threading.Lock(), but initialized lazily to avoid importing threading very early at startup,
46
+ # because there are gevent-based applications that need to be first to import threading by themselves.
47
+ # See https://github.com/pypa/virtualenv/issues/1895 for details.
48
+ lock = [] # noqa: RUF012
49
+
50
+ def find_spec(self, fullname, path, target=None): # noqa: ARG002
51
+ if fullname in _DISTUTILS_PATCH and self.fullname is None:
52
+ # initialize lock[0] lazily
53
+ if len(self.lock) == 0:
54
+ import threading
55
+
56
+ lock = threading.Lock()
57
+ # there is possibility that two threads T1 and T2 are simultaneously running into find_spec,
58
+ # observing .lock as empty, and further going into hereby initialization. However due to the GIL,
59
+ # list.append() operation is atomic and this way only one of the threads will "win" to put the lock
60
+ # - that every thread will use - into .lock[0].
61
+ # https://docs.python.org/3/faq/library.html#what-kinds-of-global-value-mutation-are-thread-safe
62
+ self.lock.append(lock)
63
+
64
+ from functools import partial
65
+ from importlib.util import find_spec
66
+
67
+ with self.lock[0]:
68
+ self.fullname = fullname
69
+ try:
70
+ spec = find_spec(fullname, path)
71
+ if spec is not None:
72
+ # https://www.python.org/dev/peps/pep-0451/#how-loading-will-work
73
+ is_new_api = hasattr(spec.loader, "exec_module")
74
+ func_name = "exec_module" if is_new_api else "load_module"
75
+ old = getattr(spec.loader, func_name)
76
+ func = self.exec_module if is_new_api else self.load_module
77
+ if old is not func:
78
+ try: # noqa: SIM105
79
+ setattr(spec.loader, func_name, partial(func, old))
80
+ except AttributeError:
81
+ pass # C-Extension loaders are r/o such as zipimporter with <3.7
82
+ return spec
83
+ finally:
84
+ self.fullname = None
85
+ return None
86
+
87
+ @staticmethod
88
+ def exec_module(old, module):
89
+ old(module)
90
+ if module.__name__ in _DISTUTILS_PATCH:
91
+ patch_dist(module)
92
+
93
+ @staticmethod
94
+ def load_module(old, name):
95
+ module = old(name)
96
+ if module.__name__ in _DISTUTILS_PATCH:
97
+ patch_dist(module)
98
+ return module
99
+
100
+
101
+ sys.meta_path.insert(0, _Finder())
.venv/lib/python3.10/site-packages/example.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #################################################################################
2
+ # Copyright (c) 2020, NVIDIA Corporation. All rights reserved. #
3
+ # #
4
+ # Redistribution and use in source and binary forms, with or without #
5
+ # modification, are permitted provided that the following conditions are met: #
6
+ # #
7
+ # * Redistributions of source code must retain the above copyright notice, #
8
+ # this list of conditions and the following disclaimer. #
9
+ # * Redistributions in binary form must reproduce the above copyright #
10
+ # notice, this list of conditions and the following disclaimer in the #
11
+ # documentation and/or other materials provided with the distribution. #
12
+ # * Neither the name of the NVIDIA Corporation nor the names of its #
13
+ # contributors may be used to endorse or promote products derived from #
14
+ # this software without specific prior written permission. #
15
+ # #
16
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" #
17
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #
18
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE #
19
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE #
20
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR #
21
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF #
22
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS #
23
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN #
24
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) #
25
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF #
26
+ # THE POSSIBILITY OF SUCH DAMAGE. #
27
+ #################################################################################
28
+
29
+ #
30
+ # Sample script to demonstrate the usage of NVML API python bindings
31
+ #
32
+
33
+ # To Run:
34
+ # $ python ./example.py
35
+
36
+ from pynvml import *
37
+
38
+ #
39
+ # Helper function
40
+ #
41
+ def StrVirt(mode):
42
+ if mode == NVML_GPU_VIRTUALIZATION_MODE_NONE:
43
+ return "None";
44
+ elif mode == NVML_GPU_VIRTUALIZATION_MODE_PASSTHROUGH:
45
+ return "Pass-Through";
46
+ elif mode == NVML_GPU_VIRTUALIZATION_MODE_VGPU:
47
+ return "VGPU";
48
+ elif mode == NVML_GPU_VIRTUALIZATION_MODE_HOST_VGPU:
49
+ return "Host VGPU";
50
+ elif mode == NVML_GPU_VIRTUALIZATION_MODE_HOST_VSGA:
51
+ return "Host VSGA";
52
+ else:
53
+ return "Unknown";
54
+
55
+ #
56
+ # Converts errors into string messages
57
+ #
58
+ def handleError(err):
59
+ if (err.value == NVML_ERROR_NOT_SUPPORTED):
60
+ return "N/A"
61
+ else:
62
+ return err.__str__()
63
+
64
+ #######
65
+ def deviceQuery():
66
+
67
+ strResult = ''
68
+ try:
69
+ #
70
+ # Initialize NVML
71
+ #
72
+ nvmlInit()
73
+
74
+ strResult += ' <driver_version>' + str(nvmlSystemGetDriverVersion()) + '</driver_version>\n'
75
+
76
+ deviceCount = nvmlDeviceGetCount()
77
+ strResult += ' <attached_gpus>' + str(deviceCount) + '</attached_gpus>\n'
78
+
79
+ for i in range(0, deviceCount):
80
+ handle = nvmlDeviceGetHandleByIndex(i)
81
+
82
+ pciInfo = nvmlDeviceGetPciInfo(handle)
83
+
84
+ strResult += ' <gpu id="%s">\n' % pciInfo.busId
85
+
86
+ strResult += ' <product_name>' + nvmlDeviceGetName(handle) + '</product_name>\n'
87
+
88
+ brandNames = {NVML_BRAND_UNKNOWN : "Unknown",
89
+ NVML_BRAND_QUADRO : "Quadro",
90
+ NVML_BRAND_TESLA : "Tesla",
91
+ NVML_BRAND_NVS : "NVS",
92
+ NVML_BRAND_GRID : "Grid",
93
+ NVML_BRAND_TITAN : "Titan",
94
+ NVML_BRAND_GEFORCE : "GeForce",
95
+ NVML_BRAND_NVIDIA_VAPPS : "NVIDIA Virtual Applications",
96
+ NVML_BRAND_NVIDIA_VPC : "NVIDIA Virtual PC",
97
+ NVML_BRAND_NVIDIA_VCS : "NVIDIA Virtual Compute Server",
98
+ NVML_BRAND_NVIDIA_VWS : "NVIDIA RTX Virtual Workstation",
99
+ NVML_BRAND_NVIDIA_CLOUD_GAMING : "NVIDIA Cloud Gaming",
100
+ NVML_BRAND_QUADRO_RTX : "Quadro RTX",
101
+ NVML_BRAND_NVIDIA_RTX : "NVIDIA RTX",
102
+ NVML_BRAND_NVIDIA : "NVIDIA",
103
+ NVML_BRAND_GEFORCE_RTX : "GeForce RTX",
104
+ NVML_BRAND_TITAN_RTX : "TITAN RTX",
105
+
106
+ }
107
+
108
+ try:
109
+ # If nvmlDeviceGetBrand() succeeds it is guaranteed to be in the dictionary
110
+ brandName = brandNames[nvmlDeviceGetBrand(handle)]
111
+ except NVMLError as err:
112
+ brandName = handleError(err)
113
+
114
+ strResult += ' <product_brand>' + brandName + '</product_brand>\n'
115
+
116
+ try:
117
+ serial = nvmlDeviceGetSerial(handle)
118
+ except NVMLError as err:
119
+ serial = handleError(err)
120
+
121
+ strResult += ' <serial>' + serial + '</serial>\n'
122
+
123
+ try:
124
+ uuid = nvmlDeviceGetUUID(handle)
125
+ except NVMLError as err:
126
+ uuid = handleError(err)
127
+
128
+ strResult += ' <uuid>' + uuid + '</uuid>\n'
129
+
130
+ strResult += ' <gpu_virtualization_mode>\n'
131
+ try:
132
+ mode = StrVirt(nvmlDeviceGetVirtualizationMode(handle))
133
+ except NVMLError as err:
134
+ mode = handleError(err)
135
+ strResult += ' <virtualization_mode>' + mode + '</virtualization_mode>\n'
136
+ strResult += ' </gpu_virtualization_mode>\n'
137
+
138
+ try:
139
+ gridLicensableFeatures = nvmlDeviceGetGridLicensableFeatures(handle)
140
+ if gridLicensableFeatures.isGridLicenseSupported == 1:
141
+ strResult += ' <vgpu_software_licensed_product>\n'
142
+ for i in range(gridLicensableFeatures.licensableFeaturesCount):
143
+ if gridLicensableFeatures.gridLicensableFeatures[i].featureState == 0:
144
+ if nvmlDeviceGetVirtualizationMode(handle) == NVML_GPU_VIRTUALIZATION_MODE_PASSTHROUGH:
145
+ strResult += ' <licensed_product_name>' + 'NVIDIA Virtual Applications' + '</licensed_product_name>\n'
146
+ strResult += ' <license_status>' + 'Licensed' + '</license_status>\n'
147
+ else:
148
+ strResult += ' <licensed_product_name>' + gridLicensableFeatures.gridLicensableFeatures[i].productName + '</licensed_product_name>\n'
149
+ strResult += ' <license_status>' + 'Unlicensed' + '</license_status>\n'
150
+ else:
151
+ strResult += ' <licensed_product_name>' + gridLicensableFeatures.gridLicensableFeatures[i].productName + '</licensed_product_name>\n'
152
+ strResult += ' <license_status>' + 'Licensed' + '</license_status>\n'
153
+ strResult += ' </vgpu_software_licensed_product>\n'
154
+ except NVMLError as err:
155
+ gridLicensableFeatures = handleError(err)
156
+
157
+ strResult += ' </gpu>\n'
158
+
159
+ except NVMLError as err:
160
+ strResult += 'example.py: ' + err.__str__() + '\n'
161
+
162
+ nvmlShutdown()
163
+
164
+ return strResult
165
+
166
+ # If this is not exectued when module is imported
167
+ if __name__ == "__main__":
168
+ print(deviceQuery())
169
+
.venv/lib/python3.10/site-packages/nvidia_ml_py-13.580.82.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ uv
.venv/lib/python3.10/site-packages/nvidia_ml_py-13.580.82.dist-info/METADATA ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: nvidia-ml-py
3
+ Version: 13.580.82
4
+ Summary: Python Bindings for the NVIDIA Management Library
5
+ Home-page: https://forums.developer.nvidia.com
6
+ Author: NVIDIA Corporation
7
+ Author-email: [email protected]
8
+ License: BSD
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Intended Audience :: System Administrators
12
+ Classifier: License :: OSI Approved :: BSD License
13
+ Classifier: Operating System :: Microsoft :: Windows
14
+ Classifier: Operating System :: POSIX :: Linux
15
+ Classifier: Programming Language :: Python
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Classifier: Topic :: System :: Hardware
18
+ Classifier: Topic :: System :: Systems Administration
19
+ Description-Content-Type: text/markdown
20
+ Dynamic: author
21
+ Dynamic: author-email
22
+ Dynamic: classifier
23
+ Dynamic: description
24
+ Dynamic: description-content-type
25
+ Dynamic: home-page
26
+ Dynamic: license
27
+ Dynamic: summary
28
+
29
+ pyNVML
30
+ ======
31
+
32
+ Python bindings to the NVIDIA Management Library
33
+ ------------------------------------------------
34
+
35
+ Provides a Python interface to GPU management and monitoring functions.
36
+
37
+ This is a wrapper around the NVML library.
38
+ For information about the NVML library, see the NVML developer page
39
+ http://developer.nvidia.com/nvidia-management-library-nvml
40
+
41
+ Download the latest package from:
42
+ http://pypi.python.org/pypi/nvidia-ml-py/
43
+
44
+ Note this file can be run with 'python -m doctest -v README.txt'
45
+ although the results are system dependent
46
+
47
+ The nvml header file contains function documentation that is relevant
48
+ to this wrapper. The header file is distributed with.
49
+ https://developer.nvidia.com/gpu-deployment-kit
50
+
51
+ The main difference is this library handles allocating structs and
52
+ passing pointers to the functions, before returning the desired value.
53
+ Non-success return codes are raised as exceptions as described in the
54
+ section below.
55
+
56
+ REQUIRES
57
+ --------
58
+ Python 2.5, or an earlier version with the ctypes module.
59
+
60
+ INSTALLATION
61
+ ------------
62
+
63
+ Pip Installation with python3:
64
+ - `python3 -m pip install nvidia-ml-py`
65
+
66
+ Manual Installation:
67
+ ```
68
+ $ tar -xzf nvidia-ml-py-$major-$minor-$patch.tar.gz`
69
+ $ cd nvidia-ml-py-$major-$minor-$patch
70
+ $ sudo python setup.py install
71
+ ```
72
+
73
+ USAGE
74
+ -----
75
+ ```
76
+ >>> from pynvml import *
77
+ >>> nvmlInit()
78
+ >>> print(f"Driver Version: {nvmlSystemGetDriverVersion()}")
79
+ Driver Version: 11.515.48
80
+ >>> deviceCount = nvmlDeviceGetCount()
81
+ >>> for i in range(deviceCount):
82
+ ... handle = nvmlDeviceGetHandleByIndex(i)
83
+ ... print(f"Device {i} : {nvmlDeviceGetName(handle)}")
84
+ ...
85
+ Device 0 : Tesla K40c
86
+
87
+ >>> nvmlShutdown()
88
+ ```
89
+
90
+ FUNCTIONS
91
+ ---------
92
+ Python methods wrap NVML functions, implemented in a C shared library.
93
+ Each function's use is the same with the following exceptions:
94
+
95
+ - Instead of returning error codes, failing error codes are raised as Python exceptions.
96
+
97
+ ```
98
+ >>> try:
99
+ ... nvmlDeviceGetCount()
100
+ ... except NVMLError as error:
101
+ ... print(error)
102
+ ...
103
+ Uninitialized
104
+ ```
105
+
106
+ - C function output parameters are returned from the corresponding Python function left to right.
107
+ ```
108
+ nvmlReturn_t nvmlDeviceGetEccMode(nvmlDevice_t device,
109
+ nvmlEnableState_t *current,
110
+ nvmlEnableState_t *pending);
111
+
112
+ >>> nvmlInit()
113
+ >>> handle = nvmlDeviceGetHandleByIndex(0)
114
+ >>> (current, pending) = nvmlDeviceGetEccMode(handle)
115
+ ```
116
+ - C structs are converted into Python classes.
117
+
118
+ ```
119
+ // C Function and typedef struct
120
+ nvmlReturn_t DECLDIR nvmlDeviceGetMemoryInfo(nvmlDevice_t device,
121
+ nvmlMemory_t *memory);
122
+ typedef struct nvmlMemory_st {
123
+ unsigned long long total;
124
+ unsigned long long free;
125
+ unsigned long long used;
126
+ } nvmlMemory_t;
127
+
128
+
129
+ # Python call to function and accessing members of ctype struct
130
+ >>> info = nvmlDeviceGetMemoryInfo(handle)
131
+ >>> print(f"Total memory: {info.total}")
132
+ Total memory: 5636292608
133
+ >>> print(f"Free memory:, {info.free}")
134
+ Free memory: 5578420224
135
+ >>> print(f"Used memory: {info.used}")
136
+ Used memory: 57872384
137
+ ```
138
+
139
+ - Python handles string buffer creation.
140
+
141
+ ```
142
+ // C Function that needs character array and length
143
+ nvmlReturn_t nvmlSystemGetDriverVersion(char* version,
144
+ unsigned int length);
145
+
146
+ # Python function handles memory
147
+ >>> version = nvmlSystemGetDriverVersion()
148
+ >>> print(version)
149
+ ... 11.520.75
150
+ >>> nvmlShutdown()
151
+ ```
152
+
153
+ For usage information see the NVML documentation.
154
+
155
+ VARIABLES
156
+ ---------
157
+ All meaningful NVML constants and enums are exposed in Python.
158
+
159
+ The NVML_VALUE_NOT_AVAILABLE constant is not used. Instead None is mapped to the field.
160
+
161
+ EXCEPTIONS
162
+ ----------
163
+ Since the C library uses return codes and python prefers exception handling, the
164
+ library converts all return codes to various exceptions. The exceptions are generated
165
+ automatically via a function at run time instead of being defined manually.
166
+
167
+ The list of exceptions can be found in NVMLError base class.
168
+
169
+ The example seen above in the FUNCTIONS section:
170
+
171
+ ```
172
+ >>> try:
173
+ ... nvmlDeviceGetCount()
174
+ ... except NVMLError as error:
175
+ ... print(error)
176
+ ...
177
+ Uninitialized
178
+ ```
179
+
180
+ Can be more accurately caught like this:
181
+
182
+ ```
183
+ >>> try:
184
+ ... nvmlDeviceGetCount()
185
+ ... except NVMLError_Uninitialized as error:
186
+ ... print(error)
187
+ ...
188
+ Uninitialized
189
+ ```
190
+
191
+ The conversion from name to exception is like this for all exceptions:
192
+ * `NVML_ERROR_UNINITIALIZED` => `NVMLError_Uninitialized`
193
+ * `NVML_ERROR_LIBRARY_NOT_FOUND` => `NVMLError_LibraryNotFound`
194
+ * `NVML_ERROR_ALREADY_INITIALIZED` => `NVMLError_AlreadyInitialized`
195
+
196
+ RELEASE NOTES
197
+ -------------
198
+ Version 2.285.0
199
+ - Added new functions for NVML 2.285. See NVML documentation for more information.
200
+ - Ported to support Python 3.0 and Python 2.0 syntax.
201
+ - Added nvidia_smi.py tool as a sample app.
202
+
203
+ Version 3.295.0
204
+ - Added new functions for NVML 3.295. See NVML documentation for more information.
205
+ - Updated nvidia_smi.py tool
206
+ - Includes additional error handling
207
+
208
+ Version 4.304.0
209
+ - Added new functions for NVML 4.304. See NVML documentation for more information.
210
+ - Updated nvidia_smi.py tool
211
+
212
+ Version 4.304.3
213
+ - Fixing nvmlUnitGetDeviceCount bug
214
+
215
+ Version 5.319.0
216
+ - Added new functions for NVML 5.319. See NVML documentation for more information.
217
+
218
+ Version 6.340.0
219
+ - Added new functions for NVML 6.340. See NVML documentation for more information.
220
+
221
+ Version 7.346.0
222
+ - Added new functions for NVML 7.346. See NVML documentation for more information.
223
+
224
+ Version 7.352.0
225
+ - Added new functions for NVML 7.352. See NVML documentation for more information.
226
+
227
+ Version 10.418
228
+ - Added new functions for NVML 10.418. See NVML documentation for more information.
229
+ - Fixed issues with using the bindings with Python 3.x
230
+ - Replaced sample app nvidia_smi.py with example.py
231
+
232
+ Version 11.515.48
233
+ - Python3 support added
234
+ - Updated API to add function new to NVML, bringing pynvml up to date with NVML
235
+ - Added auto-version to handle byte and string conversion automatically for both structs and functions
236
+ - Minor bug fixes
237
+ - Added README.txt correctly in long_description for pypi.org
238
+
239
+ Version 11.520
240
+ - Updated Long Description to be actual markdown
241
+ - Added new functions for NVML 11.520
242
+
243
+ Version 11.525
244
+ - Added new functions for NVML 11.525
245
+
246
+ Version 12.535
247
+ - Added new functions for NVML 12.535. See NVML documentation for more information.
248
+
249
+ Version 12.550
250
+ - Added new functions for NVML 12.550. See NVML documentation for more information.
251
+
252
+ Version 12.555
253
+ - Added new functions for NVML 12.555. See NVML documentation for more information.
254
+
255
+ Version 12.560
256
+ - Added new functions for NVML 12.560. See NVML documentation for more information.
257
+
258
+ Version 12.565
259
+ - Added new functions for NVML 12.565. See NVML documentation for more information.
260
+
261
+ Version 12.575
262
+ - Added new functions for NVML 12.575. See NVML documentation for more information.
263
+
264
+ Version 13.580
265
+ - Major version increased to 13.
266
+ - Several APIs are now deprecated and will be removed in a future release. Please see NVML documentation for more information.
267
+ - Added new functions for NVML 13.580. See NVML documentation for more information.
268
+
269
+ COPYRIGHT
270
+ ---------
271
+ Copyright (c) 2011-2025, NVIDIA Corporation. All rights reserved.
272
+
273
+ LICENSE
274
+ -------
275
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
276
+
277
+ - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
278
+
279
+ - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
280
+
281
+ - Neither the name of the NVIDIA Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
282
+
283
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
284
+
.venv/lib/python3.10/site-packages/nvidia_ml_py-13.580.82.dist-info/RECORD ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ example.py,sha256=mDXwPVyEDuiKeMApEh53r_M36xuncmzMpFOGA3Q-_Kw,7968
2
+ nvidia_ml_py-13.580.82.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
3
+ nvidia_ml_py-13.580.82.dist-info/METADATA,sha256=efN4BCMX6ch9fgSsWKVGrI5wmUikeXL62QUO3KutF8Y,9578
4
+ nvidia_ml_py-13.580.82.dist-info/RECORD,,
5
+ nvidia_ml_py-13.580.82.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ nvidia_ml_py-13.580.82.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
7
+ nvidia_ml_py-13.580.82.dist-info/top_level.txt,sha256=wLINSA1WKnhsGgKsb_nuj51ZCQrXaN5qhioTL56g98A,15
8
+ pynvml.py,sha256=QlFCnCXxYVpBZvOV08Cf4HMr-wI4ZMS38SgTNz5Wluo,264920
.venv/lib/python3.10/site-packages/nvidia_ml_py-13.580.82.dist-info/REQUESTED ADDED
File without changes
.venv/lib/python3.10/site-packages/nvidia_ml_py-13.580.82.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
.venv/lib/python3.10/site-packages/nvidia_ml_py-13.580.82.dist-info/top_level.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ example
2
+ pynvml
.venv/lib/python3.10/site-packages/nvitop-1.5.3.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ uv
.venv/lib/python3.10/site-packages/nvitop-1.5.3.dist-info/METADATA ADDED
@@ -0,0 +1,1563 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: nvitop
3
+ Version: 1.5.3
4
+ Summary: An interactive NVIDIA-GPU process viewer and beyond, the one-stop solution for GPU process management.
5
+ Author-email: Xuehai Pan <[email protected]>
6
+ License: Apache-2.0 AND GPL-3.0-only
7
+ Project-URL: Homepage, https://github.com/XuehaiPan/nvitop
8
+ Project-URL: Repository, https://github.com/XuehaiPan/nvitop
9
+ Project-URL: Documentation, https://nvitop.readthedocs.io
10
+ Project-URL: Bug Report, https://github.com/XuehaiPan/nvitop/issues
11
+ Keywords: nvidia,nvidia-smi,NVIDIA,NVML,CUDA,GPU,top,monitoring
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Operating System :: Microsoft :: Windows
24
+ Classifier: Operating System :: POSIX :: Linux
25
+ Classifier: Environment :: GPU
26
+ Classifier: Environment :: GPU :: NVIDIA CUDA
27
+ Classifier: Environment :: Console
28
+ Classifier: Environment :: Console :: Curses
29
+ Classifier: Intended Audience :: Developers
30
+ Classifier: Intended Audience :: End Users/Desktop
31
+ Classifier: Intended Audience :: System Administrators
32
+ Classifier: Topic :: System :: Hardware
33
+ Classifier: Topic :: System :: Monitoring
34
+ Classifier: Topic :: System :: Systems Administration
35
+ Classifier: Topic :: Utilities
36
+ Requires-Python: >=3.8
37
+ Description-Content-Type: text/markdown
38
+ License-File: LICENSE
39
+ License-File: COPYING
40
+ Requires-Dist: nvidia-ml-py<13.581.0a0,>=11.450.51
41
+ Requires-Dist: psutil>=5.6.6
42
+ Requires-Dist: colorama>=0.4.0; platform_system == "Windows"
43
+ Requires-Dist: windows-curses>=2.2.0; platform_system == "Windows"
44
+ Provides-Extra: lint
45
+ Requires-Dist: ruff; extra == "lint"
46
+ Requires-Dist: pylint[spelling]; extra == "lint"
47
+ Requires-Dist: xdoctest; extra == "lint"
48
+ Requires-Dist: mypy; extra == "lint"
49
+ Requires-Dist: typing-extensions; extra == "lint"
50
+ Requires-Dist: pre-commit; extra == "lint"
51
+ Provides-Extra: cuda10
52
+ Requires-Dist: nvidia-ml-py==11.450.51; extra == "cuda10"
53
+ Provides-Extra: cuda11
54
+ Requires-Dist: nvidia-ml-py<=11.525.150,>=11.450.51; extra == "cuda11"
55
+ Provides-Extra: cuda12
56
+ Requires-Dist: nvidia-ml-py<=12.575.51,>=12.535.77; extra == "cuda12"
57
+ Provides-Extra: cuda13
58
+ Requires-Dist: nvidia-ml-py==13.580.65; extra == "cuda13"
59
+ Dynamic: license-file
60
+ Dynamic: provides-extra
61
+
62
+ # nvitop
63
+
64
+ <!-- markdownlint-disable html -->
65
+
66
+ ![Python 3.8+](https://img.shields.io/badge/Python-3.8%2B-brightgreen)
67
+ [![PyPI](https://img.shields.io/pypi/v/nvitop?label=pypi&logo=pypi)](https://pypi.org/project/nvitop)
68
+ [![conda-forge](https://img.shields.io/conda/vn/conda-forge/nvitop?label=conda&logo=condaforge)](https://anaconda.org/conda-forge/nvitop)
69
+ [![Documentation Status](https://img.shields.io/readthedocs/nvitop?label=docs&logo=readthedocs)](https://nvitop.readthedocs.io)
70
+ [![Downloads](https://static.pepy.tech/personalized-badge/nvitop?period=total&left_color=grey&right_color=blue&left_text=downloads)](https://pepy.tech/project/nvitop)
71
+ [![GitHub Repo Stars](https://img.shields.io/github/stars/XuehaiPan/nvitop?label=stars&logo=github&color=brightgreen)](https://github.com/XuehaiPan/nvitop/stargazers)
72
+ [![License](https://img.shields.io/github/license/XuehaiPan/nvitop?label=license&logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0IiBmaWxsPSIjZmZmZmZmIj48cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMi43NSAyLjc1YS43NS43NSAwIDAwLTEuNSAwVjQuNUg5LjI3NmExLjc1IDEuNzUgMCAwMC0uOTg1LjMwM0w2LjU5NiA1Ljk1N0EuMjUuMjUgMCAwMTYuNDU1IDZIMi4zNTNhLjc1Ljc1IDAgMTAwIDEuNUgzLjkzTC41NjMgMTUuMThhLjc2Mi43NjIgMCAwMC4yMS44OGMuMDguMDY0LjE2MS4xMjUuMzA5LjIyMS4xODYuMTIxLjQ1Mi4yNzguNzkyLjQzMy42OC4zMTEgMS42NjIuNjIgMi44NzYuNjJhNi45MTkgNi45MTkgMCAwMDIuODc2LS42MmMuMzQtLjE1NS42MDYtLjMxMi43OTItLjQzMy4xNS0uMDk3LjIzLS4xNTguMzEtLjIyM2EuNzUuNzUgMCAwMC4yMDktLjg3OEw1LjU2OSA3LjVoLjg4NmMuMzUxIDAgLjY5NC0uMTA2Ljk4NC0uMzAzbDEuNjk2LTEuMTU0QS4yNS4yNSAwIDAxOS4yNzUgNmgxLjk3NXYxNC41SDYuNzYzYS43NS43NSAwIDAwMCAxLjVoMTAuNDc0YS43NS43NSAwIDAwMC0xLjVIMTIuNzVWNmgxLjk3NGMuMDUgMCAuMS4wMTUuMTQuMDQzbDEuNjk3IDEuMTU0Yy4yOS4xOTcuNjMzLjMwMy45ODQuMzAzaC44ODZsLTMuMzY4IDcuNjhhLjc1Ljc1IDAgMDAuMjMuODk2Yy4wMTIuMDA5IDAgMCAuMDAyIDBhMy4xNTQgMy4xNTQgMCAwMC4zMS4yMDZjLjE4NS4xMTIuNDUuMjU2Ljc5LjRhNy4zNDMgNy4zNDMgMCAwMDIuODU1LjU2OCA3LjM0MyA3LjM0MyAwIDAwMi44NTYtLjU2OWMuMzM4LS4xNDMuNjA0LS4yODcuNzktLjM5OWEzLjUgMy41IDAgMDAuMzEtLjIwNi43NS43NSAwIDAwLjIzLS44OTZMMjAuMDcgNy41aDEuNTc4YS43NS43NSAwIDAwMC0xLjVoLTQuMTAyYS4yNS4yNSAwIDAxLS4xNC0uMDQzbC0xLjY5Ny0xLjE1NGExLjc1IDEuNzUgMCAwMC0uOTg0LS4zMDNIMTIuNzVWMi43NXpNMi4xOTMgMTUuMTk4YTUuNDE4IDUuNDE4IDAgMDAyLjU1Ny42MzUgNS40MTggNS40MTggMCAwMDIuNTU3LS42MzVMNC43NSA5LjM2OGwtMi41NTcgNS44M3ptMTQuNTEtLjAyNGMuMDgyLjA0LjE3NC4wODMuMjc1LjEyNi41My4yMjMgMS4zMDUuNDUgMi4yNzIuNDVhNS44NDYgNS44NDYgMCAwMDIuNTQ3LS41NzZMMTkuMjUgOS4zNjdsLTIuNTQ3IDUuODA3eiI+PC9wYXRoPjwvc3ZnPgo=)](#license)
73
+
74
+ An interactive NVIDIA-GPU process viewer and beyond, the one-stop solution for GPU process management. The full API references host at <https://nvitop.readthedocs.io>.
75
+
76
+ <p align="center">
77
+ <img width="100%" src="https://user-images.githubusercontent.com/16078332/171005261-1aad126e-dc27-4ed3-a89b-7f9c1c998bf7.png" alt="Monitor">
78
+ <br/>
79
+ Monitor mode of <code>nvitop</code>.
80
+ <br/>
81
+ (TERM: GNOME Terminal / OS: Ubuntu 16.04 LTS (over SSH) / Locale: <code>en_US.UTF-8</code>)
82
+ </p>
83
+
84
+ <p align="center">
85
+ <a href="./nvitop-exporter">
86
+ <img width="100%" src="https://github.com/user-attachments/assets/e4867e64-2ca9-45bc-b524-929053f9673d" alt="Grafana Dashboard">
87
+ </a>
88
+ <br/>
89
+ A Grafana dashboard built on top of <code>nvitop-exporter</code>.
90
+ </p>
91
+
92
+ ### Table of Contents <!-- omit in toc --> <!-- markdownlint-disable heading-increment -->
93
+
94
+ - [Features](#features)
95
+ - [Requirements](#requirements)
96
+ - [Installation](#installation)
97
+ - [Usage](#usage)
98
+ - [Device and Process Status](#device-and-process-status)
99
+ - [Resource Monitor](#resource-monitor)
100
+ - [For Docker Users](#for-docker-users)
101
+ - [For SSH Users](#for-ssh-users)
102
+ - [Command Line Options and Environment Variables](#command-line-options-and-environment-variables)
103
+ - [Keybindings for Monitor Mode](#keybindings-for-monitor-mode)
104
+ - [CUDA Visible Devices Selection Tool](#cuda-visible-devices-selection-tool)
105
+ - [Callback Functions for Machine Learning Frameworks (DEPRECATED)](#callback-functions-for-machine-learning-frameworks-deprecated)
106
+ - [Callback for TensorFlow (Keras)](#callback-for-tensorflow-keras)
107
+ - [Callback for PyTorch Lightning](#callback-for-pytorch-lightning)
108
+ - [TensorBoard Integration](#tensorboard-integration)
109
+ - [More than a Monitor](#more-than-a-monitor)
110
+ - [Quick Start](#quick-start)
111
+ - [Status Snapshot](#status-snapshot)
112
+ - [Resource Metric Collector](#resource-metric-collector)
113
+ - [Low-level APIs](#low-level-apis)
114
+ - [Device](#device)
115
+ - [Process](#process)
116
+ - [Host (inherited from psutil)](#host-inherited-from-psutil)
117
+ - [Screenshots](#screenshots)
118
+ - [Changelog](#changelog)
119
+ - [License](#license)
120
+ - [Copyright Notice](#copyright-notice)
121
+
122
+ ------
123
+
124
+ `nvitop` is an interactive NVIDIA device and process monitoring tool. It has a colorful and informative interface that continuously updates the status of the devices and processes. As a resource monitor, it includes many features and options, such as tree-view, environment variable viewing, process filtering, process metrics monitoring, etc. Beyond that, the package also ships a [CUDA device selection tool `nvisel`](#cuda-visible-devices-selection-tool) for deep learning researchers. It also provides handy APIs that allow developers to write their own monitoring tools. Please refer to section [More than a Monitor](#more-than-a-monitor) and the full API references at <https://nvitop.readthedocs.io> for more information.
125
+
126
+ <p align="center">
127
+ <img width="100%" src="https://user-images.githubusercontent.com/16078332/202362811-34f2c01d-97c8-49d2-b19b-0d7da648f2d5.png" alt="Filter">
128
+ <br/>
129
+ Process filtering and a more colorful interface.
130
+ </p>
131
+
132
+ <p align="center">
133
+ <img width="100%" src="https://user-images.githubusercontent.com/16078332/202362686-859bf4ad-6237-46ca-b2f7-f547d2f63213.png" alt="Comparison">
134
+ <br/>
135
+ Compare to <code>nvidia-smi</code>.
136
+ </p>
137
+
138
+ ------
139
+
140
+ ## Features
141
+
142
+ - **Informative and fancy output**: show more information than `nvidia-smi` with colorized fancy box drawing.
143
+ - **Monitor mode**: can run as a resource monitor, rather than print the results only once.
144
+ - bar charts and history graphs
145
+ - process sorting
146
+ - process filtering
147
+ - send signals to processes with a keystroke
148
+ - tree-view screen for GPU processes and their parent processes
149
+ - environment variable screen
150
+ - help screen
151
+ - mouse support
152
+ - **Interactive**: responsive for user input (from keyboard and/or mouse) in monitor mode. (vs. [gpustat](https://github.com/wookayin/gpustat) & [py3nvml](https://github.com/fbcotter/py3nvml))
153
+ - **Efficient**:
154
+ - query device status using [*NVML Python bindings*](https://pypi.org/project/nvidia-ml-py) directly, instead of parsing the output of `nvidia-smi`. (vs. [nvidia-htop](https://github.com/peci1/nvidia-htop))
155
+ - support sparse query and cache results with `TTLCache` from [cachetools](https://github.com/tkem/cachetools). (vs. [gpustat](https://github.com/wookayin/gpustat))
156
+ - display information using the `curses` library rather than `print` with ANSI escape codes. (vs. [py3nvml](https://github.com/fbcotter/py3nvml))
157
+ - asynchronously gather information using multi-threading and correspond to user input much faster. (vs. [nvtop](https://github.com/Syllo/nvtop))
158
+ - **Portable**: work on both Linux and Windows.
159
+ - get host process information using the cross-platform library [psutil](https://github.com/giampaolo/psutil) instead of calling `ps -p <pid>` in a subprocess. (vs. [nvidia-htop](https://github.com/peci1/nvidia-htop) & [py3nvml](https://github.com/fbcotter/py3nvml))
160
+ - written in pure Python, easy to install with `pip`. (vs. [nvtop](https://github.com/Syllo/nvtop))
161
+ - **Integrable**: easy to integrate into other applications, more than monitoring. (vs. [nvidia-htop](https://github.com/peci1/nvidia-htop) & [nvtop](https://github.com/Syllo/nvtop))
162
+
163
+ <p align="center">
164
+ <img width="100%" src="https://user-images.githubusercontent.com/16078332/129374533-fe06c01a-630d-4994-b54b-821cccd0d33c.png" alt="Windows">
165
+ <br/>
166
+ <code>nvitop</code> supports Windows!
167
+ <br/>
168
+ (SHELL: PowerShell / TERM: Windows Terminal / OS: Windows 10 / Locale: <code>en-US</code>)
169
+ </p>
170
+
171
+ ------
172
+
173
+ ## Requirements
174
+
175
+ - Python 3.8+
176
+ - NVIDIA Management Library (NVML)
177
+ - nvidia-ml-py
178
+ - psutil
179
+ - curses<sup>[*](#curses)</sup> (with `libncursesw`)
180
+
181
+ **NOTE:** The [NVIDIA Management Library (*NVML*)](https://developer.nvidia.com/nvidia-management-library-nvml) is a C-based programmatic interface for monitoring and managing various states. The runtime version of the NVML library ships with the NVIDIA display driver (available at [Download Drivers | NVIDIA](https://www.nvidia.com/Download/index.aspx)), or can be downloaded as part of the NVIDIA CUDA Toolkit (available at [CUDA Toolkit | NVIDIA Developer](https://developer.nvidia.com/cuda-downloads)). The lists of OS platforms and NVIDIA-GPUs supported by the NVML library can be found in the [NVML API Reference](https://docs.nvidia.com/deploy/nvml-api/nvml-api-reference.html).
182
+
183
+ This repository contains a Bash script to install/upgrade the NVIDIA drivers for Ubuntu Linux. For example:
184
+
185
+ ```bash
186
+ git clone --depth=1 https://github.com/XuehaiPan/nvitop.git && cd nvitop
187
+
188
+ # Change to tty3 console (required for desktop users with GUI (tty2))
189
+ # Optional for SSH users
190
+ sudo chvt 3 # or use keyboard shortcut: Ctrl-LeftAlt-F3
191
+
192
+ bash install-nvidia-driver.sh --package=nvidia-driver-470 # install the R470 driver from ppa:graphics-drivers
193
+ bash install-nvidia-driver.sh --latest # install the latest driver from ppa:graphics-drivers
194
+ ```
195
+
196
+ <p align="center">
197
+ <img width="100%" src="https://user-images.githubusercontent.com/16078332/174480112-e9a35edc-8f42-438e-a103-1d0ce998b381.png" alt="install-nvidia-driver">
198
+ <br/>
199
+ NVIDIA driver installer for Ubuntu Linux.
200
+ </p>
201
+
202
+ Run `bash install-nvidia-driver.sh --help` for more information.
203
+
204
+ <a name="curses">*</a> The `curses` library is a built-in module of Python on Unix-like systems, and it is supported by a third-party package called `windows-curses` on Windows using PDCurses. Inconsistent behavior of `nvitop` may occur on different terminal emulators on Windows, such as missing mouse support.
205
+
206
+ ------
207
+
208
+ ## Installation
209
+
210
+ **It is highly recommended to install `nvitop` in an isolated virtual environment.** Simple installation and run via [`uvx`](https://docs.astral.sh/uv/guides/tools) (a.k.a. `uv tool run`) or [`pipx`](https://pypa.github.io/pipx):
211
+
212
+ ```bash
213
+ uvx nvitop
214
+ # or
215
+ pipx run nvitop
216
+ ```
217
+
218
+ You can also set this command as an alias in your shell startup file, e.g.:
219
+
220
+ ```bash
221
+ # For Bash
222
+ echo 'alias nvitop="uvx nvitop"' >> ~/.bashrc
223
+
224
+ # For Zsh
225
+ echo 'alias nvitop="uvx nvitop"' >> ~/.zshrc
226
+
227
+ # For Fish
228
+ mkdir -p ~/.config/fish
229
+ echo 'alias nvitop="uvx nvitop"' >> ~/.config/fish/config.fish
230
+
231
+ # For PowerShell
232
+ New-Item -Path (Split-Path -Parent -Path $PROFILE.CurrentUserAllHosts) -ItemType Directory -Force
233
+ 'Function nvitop { uvx nvitop @Args }' >> $PROFILE.CurrentUserAllHosts
234
+ ```
235
+
236
+ or
237
+
238
+ ```bash
239
+ # For Bash
240
+ echo 'alias nvitop="pipx run nvitop"' >> ~/.bashrc
241
+
242
+ # For Zsh
243
+ echo 'alias nvitop="pipx run nvitop"' >> ~/.zshrc
244
+
245
+ # For Fish
246
+ mkdir -p ~/.config/fish
247
+ echo 'alias nvitop="pipx run nvitop"' >> ~/.config/fish/config.fish
248
+
249
+ # For PowerShell
250
+ New-Item -Path (Split-Path -Parent -Path $PROFILE.CurrentUserAllHosts) -ItemType Directory -Force
251
+ 'Function nvitop { pipx run nvitop @Args }' >> $PROFILE.CurrentUserAllHosts
252
+ ```
253
+
254
+ Install from PyPI ([![PyPI](https://img.shields.io/pypi/v/nvitop?label=pypi&logo=pypi)](https://pypi.org/project/nvitop)):
255
+
256
+ ```bash
257
+ pip3 install --upgrade nvitop
258
+ ```
259
+
260
+ Install from conda-forge ([![conda-forge](https://img.shields.io/conda/v/conda-forge/nvitop?logo=condaforge)](https://anaconda.org/conda-forge/nvitop)):
261
+
262
+ ```bash
263
+ conda install -c conda-forge nvitop
264
+ ```
265
+
266
+ Install the latest version from GitHub (![Commit Count](https://img.shields.io/github/commits-since/XuehaiPan/nvitop/v1.5.3)):
267
+
268
+ ```bash
269
+ pip3 install --upgrade pip setuptools
270
+ pip3 install git+https://github.com/XuehaiPan/nvitop.git#egg=nvitop
271
+ ```
272
+
273
+ Or, clone this repo and install manually:
274
+
275
+ ```bash
276
+ git clone --depth=1 https://github.com/XuehaiPan/nvitop.git
277
+ cd nvitop
278
+ pip3 install .
279
+ ```
280
+
281
+ **NOTE:** If you encounter the *"nvitop: command not found"* error after installation, please check whether you have added the Python console script path (e.g., `"${HOME}/.local/bin"`) to your `PATH` environment variable. Alternatively, you can use `python3 -m nvitop`.
282
+
283
+ <p align="center">
284
+ <img width="100%" src="https://user-images.githubusercontent.com/16078332/178963038-a5cd4eb5-02a8-4456-966f-d5ff04eb44d8.png" alt="MIG Device Support">
285
+ <br/>
286
+ MIG Device Support.
287
+ <br/>
288
+ </p>
289
+
290
+ ------
291
+
292
+ ## Usage
293
+
294
+ ### Device and Process Status
295
+
296
+ Query the device and process status. The output is similar to `nvidia-smi`, but has been enriched and colorized.
297
+
298
+ ```bash
299
+ # Query the status of all devices
300
+ $ nvitop -1 # or use `python3 -m nvitop -1`
301
+
302
+ # Specify query devices (by integer indices)
303
+ $ nvitop -1 -o 0 1 # only show <GPU 0> and <GPU 1>
304
+
305
+ # Only show devices in `CUDA_VISIBLE_DEVICES` (by integer indices or UUID strings)
306
+ $ nvitop -1 -ov
307
+
308
+ # Only show GPU processes with the compute context (type: 'C' or 'C+G')
309
+ $ nvitop -1 -c
310
+ ```
311
+
312
+ When the `-1` switch is on, the result will be displayed **ONLY ONCE** (same as the default behavior of `nvidia-smi`). This is much faster and has lower resource usage. See [Command Line Options](#command-line-options-and-environment-variables) for more command options.
313
+
314
+ There is also a CLI tool called `nvisel` that ships with the `nvitop` PyPI package. See [CUDA Visible Devices Selection Tool](#cuda-visible-devices-selection-tool) for more information.
315
+
316
+ ### Resource Monitor
317
+
318
+ Run as a resource monitor:
319
+
320
+ ```bash
321
+ # Monitor mode (when the display mode is omitted, `NVITOP_MONITOR_MODE` will be used)
322
+ $ nvitop # or use `python3 -m nvitop`
323
+
324
+ # Automatically configure the display mode according to the terminal size
325
+ $ nvitop -m auto # shortcut: `a` key
326
+
327
+ # Arbitrarily display as `full` mode
328
+ $ nvitop -m full # shortcut: `f` key
329
+
330
+ # Arbitrarily display as `compact` mode
331
+ $ nvitop -m compact # shortcut: `c` key
332
+
333
+ # Specify query devices (by integer indices)
334
+ $ nvitop -o 0 1 # only show <GPU 0> and <GPU 1>
335
+
336
+ # Only show devices in `CUDA_VISIBLE_DEVICES` (by integer indices or UUID strings)
337
+ $ nvitop -ov
338
+
339
+ # Only show GPU processes with the compute context (type: 'C' or 'C+G')
340
+ $ nvitop -c
341
+
342
+ # Use ASCII characters only
343
+ $ nvitop -U # useful for terminals without Unicode support
344
+
345
+ # For light terminals
346
+ $ nvitop --light
347
+
348
+ # For spectrum-like bar charts (requires the terminal supports 256-color)
349
+ $ nvitop --colorful
350
+ ```
351
+
352
+ You can configure the default monitor mode with the `NVITOP_MONITOR_MODE` environment variable (default `auto` if not set). See [Command Line Options and Environment Variables](#command-line-options-and-environment-variables) for more command options.
353
+
354
+ In monitor mode, you can use <kbd>Ctrl-c</kbd> / <kbd>T</kbd> / <kbd>K</kbd> keys to interrupt / terminate / kill a process. And it's recommended to *terminate* or *kill* a process in the **tree-view screen** (shortcut: <kbd>t</kbd>). For normal users, `nvitop` will shallow other users' processes (in low-intensity colors). For **system administrators**, you can use `sudo nvitop` to terminate other users' processes.
355
+
356
+ Also, to enter the process metrics screen, select a process and then press the <kbd>Enter</kbd> / <kbd>Return</kbd> key . `nvitop` dynamically displays the process metrics with live graphs.
357
+
358
+ <p align="center">
359
+ <img width="100%" src="https://user-images.githubusercontent.com/16078332/192108815-37c03705-be44-47d4-9908-6d05175db230.png" alt="Process Metrics Screen">
360
+ <br/>
361
+ Watch metrics for a specific process (shortcut: <kbd>Enter</kbd> / <kbd>Return</kbd>).
362
+ </p>
363
+
364
+ Press <kbd>h</kbd> for help or <kbd>q</kbd> to return to the terminal. See [Keybindings for Monitor Mode](#keybindings-for-monitor-mode) for more shortcuts.
365
+
366
+ <p align="center">
367
+ <img width="100%" src="https://user-images.githubusercontent.com/16078332/192108664-61f1983c-6f62-48e6-87c5-29633d9c409e.png" alt="Help Screen">
368
+ <br/>
369
+ <code>nvitop</code> comes with a help screen (shortcut: <kbd>h</kbd>).
370
+ </p>
371
+
372
+ #### For Docker Users
373
+
374
+ Build and run the Docker image with [nvidia-container-toolkit](https://github.com/NVIDIA/nvidia-container-toolkit):
375
+
376
+ ```bash
377
+ git clone --depth=1 https://github.com/XuehaiPan/nvitop.git && cd nvitop # clone this repo first
378
+ docker build --tag nvitop:latest . # build the Docker image
379
+ docker run -it --rm --runtime=nvidia --gpus=all --pid=host nvitop:latest # run the Docker container
380
+ ```
381
+
382
+ **NOTE:** Don't forget to add the `--pid=host` option when running the container.
383
+
384
+ If you only need to set up the Grafana dashboard, you can start a dashboard at [`http://localhost:3000`](http://localhost:3000) with the following command:
385
+
386
+ ```bash
387
+ docker compose --project-directory=nvitop-exporter/grafana up --build --detach
388
+ ```
389
+
390
+ See [`nvitop-exporter`](./nvitop-exporter/README.md) for more details.
391
+
392
+ #### For SSH Users
393
+
394
+ Run `nvitop` directly on the SSH session instead of a login shell:
395
+
396
+ ```bash
397
+ ssh user@host -t nvitop # installed by `sudo pip3 install ...`
398
+ ssh user@host -t '~/.local/bin/nvitop' # installed by `pip3 install --user ...`
399
+ ```
400
+
401
+ **NOTE:** Users need to add the `-t` option to allocate a pseudo-terminal over the SSH session for monitor mode.
402
+
403
+ #### Command Line Options and Environment Variables
404
+
405
+ Type `nvitop --help` for more command options:
406
+
407
+ ```text
408
+ usage: nvitop [--help] [--version] [--once | --monitor [{auto,full,compact}]]
409
+ [--interval SEC] [--ascii] [--colorful] [--force-color] [--light]
410
+ [--gpu-util-thresh th1 th2] [--mem-util-thresh th1 th2]
411
+ [--only INDEX [INDEX ...]] [--only-visible]
412
+ [--compute] [--only-compute] [--graphics] [--only-graphics]
413
+ [--user [USERNAME ...]] [--pid PID [PID ...]]
414
+
415
+ An interactive NVIDIA-GPU process viewer.
416
+
417
+ options:
418
+ --help, -h Show this help message and exit.
419
+ --version, -V Show nvitop's version number and exit.
420
+ --once, -1 Report query data only once.
421
+ --monitor [{auto,full,compact}], -m [{auto,full,compact}]
422
+ Run as a resource monitor. Continuously report query data and handle user inputs.
423
+ If the argument is omitted, the value from `NVITOP_MONITOR_MODE` will be used.
424
+ (default fallback mode: auto)
425
+ --interval SEC Process status update interval in seconds. (default: 2)
426
+ --ascii, --no-unicode, -U
427
+ Use ASCII characters only, which is useful for terminals without Unicode support.
428
+
429
+ coloring:
430
+ --colorful Use gradient colors to get spectrum-like bar charts. This option is only available
431
+ when the terminal supports 256 colors. You may need to set environment variable
432
+ `TERM="xterm-256color"`. Note that the terminal multiplexer, such as `tmux`, may
433
+ override the `TREM` variable.
434
+ --force-color Force colorize even when `stdout` is not a TTY terminal.
435
+ --light Tweak visual results for light theme terminals in monitor mode.
436
+ Set variable `NVITOP_MONITOR_MODE="light"` on light terminals for convenience.
437
+ --gpu-util-thresh th1 th2
438
+ Thresholds of GPU utilization to determine the load intensity.
439
+ Coloring rules: light < th1 % <= moderate < th2 % <= heavy.
440
+ ( 1 <= th1 < th2 <= 99, defaults: 10 75 )
441
+ --mem-util-thresh th1 th2
442
+ Thresholds of GPU memory percent to determine the load intensity.
443
+ Coloring rules: light < th1 % <= moderate < th2 % <= heavy.
444
+ ( 1 <= th1 < th2 <= 99, defaults: 10 80 )
445
+
446
+ device filtering:
447
+ --only INDEX [INDEX ...], -o INDEX [INDEX ...]
448
+ Only show the specified devices, suppress option `--only-visible`.
449
+ --only-visible, -ov Only show devices in the `CUDA_VISIBLE_DEVICES` environment variable.
450
+
451
+ process filtering:
452
+ --compute, -c Only show GPU processes with the compute context. (type: 'C' or 'C+G')
453
+ --only-compute, -C Only show GPU processes exactly with the compute context. (type: 'C' only)
454
+ --graphics, -g Only show GPU processes with the graphics context. (type: 'G' or 'C+G')
455
+ --only-graphics, -G Only show GPU processes exactly with the graphics context. (type: 'G' only)
456
+ --user [USERNAME ...], -u [USERNAME ...]
457
+ Only show processes of the given users (or `$USER` for no argument).
458
+ --pid PID [PID ...], -p PID [PID ...]
459
+ Only show processes of the given PIDs.
460
+ ```
461
+
462
+ `nvitop` can accept the following environment variables for monitor mode:
463
+
464
+ | Name | Description | Valid Values | Default Value |
465
+ | -------------------------------------- | --------------------------------------------------- | ----------------------------------------------------------------------- | ----------------- |
466
+ | `NVITOP_MONITOR_MODE` | The default display mode (a comma-separated string) | `auto` / `full` / `compact`<br>`plain` / `colorful`<br>`dark` / `light` | `auto,plain,dark` |
467
+ | `NVITOP_GPU_UTILIZATION_THRESHOLDS` | Thresholds of GPU utilization | `10,75` , `1,99`, ... | `10,75` |
468
+ | `NVITOP_MEMORY_UTILIZATION_THRESHOLDS` | Thresholds of GPU memory percent | `10,80` , `1,99`, ... | `10,80` |
469
+ | `LOGLEVEL` | Log level for log messages | `DEBUG` , `INFO`, `WARNING`, ... | `WARNING` |
470
+
471
+ For example:
472
+
473
+ ```bash
474
+ # Replace the following export statements if you are not using Bash / Zsh
475
+ export NVITOP_MONITOR_MODE="full,light"
476
+
477
+ # Full monitor mode with light terminal tweaks
478
+ nvitop
479
+ ```
480
+
481
+ For convenience, you can add these environment variables to your shell startup file, e.g.:
482
+
483
+ ```bash
484
+ # For Bash
485
+ echo 'export NVITOP_MONITOR_MODE="full"' >> ~/.bashrc
486
+
487
+ # For Zsh
488
+ echo 'export NVITOP_MONITOR_MODE="full"' >> ~/.zshrc
489
+
490
+ # For Fish
491
+ echo 'set -gx NVITOP_MONITOR_MODE "full"' >> ~/.config/fish/config.fish
492
+
493
+ # For PowerShell
494
+ '$Env:NVITOP_MONITOR_MODE = "full"' >> $PROFILE.CurrentUserAllHosts
495
+ ```
496
+
497
+ #### Keybindings for Monitor Mode
498
+
499
+ | Key | Binding |
500
+ | -------------------------------------------------------------------------: | :----------------------------------------------------------------------------------- |
501
+ | `q` | Quit and return to the terminal. |
502
+ | `h` / `?` | Go to the help screen. |
503
+ | `a` / `f` / `c` | Change the display mode to *auto* / *full* / *compact*. |
504
+ | `r` / `<C-r>` / `<F5>` | Force refresh the window. |
505
+ | | |
506
+ | `<Up>` / `<Down>`<br>`<A-k>` / `<A-j>`<br>`<Tab>` / `<S-Tab>`<br>`<Wheel>` | Select and highlight a process. |
507
+ | `<Left>` / `<Right>`<br>`<A-h>` / `<A-l>`<br>`<S-Wheel>` | Scroll the host information of processes. |
508
+ | `<Home>` | Select the first process. |
509
+ | `<End>` | Select the last process. |
510
+ | `<C-a>`<br>`^` | Scroll left to the beginning of the process entry (i.e. beginning of line). |
511
+ | `<C-e>`<br>`$` | Scroll right to the end of the process entry (i.e. end of line). |
512
+ | `<PageUp>` / `<PageDown>`<br/> `<A-K>` / `<A-J>`<br>`[` / `]` | scroll entire screen (for large amounts of processes). |
513
+ | | |
514
+ | `<Space>` | Tag/untag current process. |
515
+ | `<Esc>` | Clear process selection. |
516
+ | `<C-c>`<br>`I` | Send `signal.SIGINT` to the selected process (interrupt). |
517
+ | `T` | Send `signal.SIGTERM` to the selected process (terminate). |
518
+ | `K` | Send `signal.SIGKILL` to the selected process (kill). |
519
+ | | |
520
+ | `e` | Show process environment. |
521
+ | `t` | Toggle tree-view screen. |
522
+ | `<Enter>` | Show process metrics. |
523
+ | | |
524
+ | `,` / `.` | Select the sort column. |
525
+ | `/` | Reverse the sort order. |
526
+ | `on` (`oN`) | Sort processes in the natural order, i.e., in ascending (descending) order of `GPU`. |
527
+ | `ou` (`oU`) | Sort processes by `USER` in ascending (descending) order. |
528
+ | `op` (`oP`) | Sort processes by `PID` in descending (ascending) order. |
529
+ | `og` (`oG`) | Sort processes by `GPU-MEM` in descending (ascending) order. |
530
+ | `os` (`oS`) | Sort processes by `%SM` in descending (ascending) order. |
531
+ | `oc` (`oC`) | Sort processes by `%CPU` in descending (ascending) order. |
532
+ | `om` (`oM`) | Sort processes by `%MEM` in descending (ascending) order. |
533
+ | `ot` (`oT`) | Sort processes by `TIME` in descending (ascending) order. |
534
+
535
+ **HINT:** It's recommended to terminate or kill a process in the tree-view screen (shortcut: <kbd>t</kbd>).
536
+
537
+ ------
538
+
539
+ ### CUDA Visible Devices Selection Tool
540
+
541
+ Automatically select `CUDA_VISIBLE_DEVICES` from the given criteria. Example usage of the CLI tool:
542
+
543
+ ```console
544
+ # All devices but sorted
545
+ $ nvisel # or use `python3 -m nvitop.select`
546
+ 6,5,4,3,2,1,0,7,8
547
+
548
+ # A simple example to select 4 devices
549
+ $ nvisel -n 4 # or use `python3 -m nvitop.select -n 4`
550
+ 6,5,4,3
551
+
552
+ # Select available devices that satisfy the given constraints
553
+ $ nvisel --min-count 2 --max-count 3 --min-free-memory 5GiB --max-gpu-utilization 60
554
+ 6,5,4
555
+
556
+ # Set `CUDA_VISIBLE_DEVICES` environment variable using `nvisel`
557
+ $ export CUDA_DEVICE_ORDER="PCI_BUS_ID" CUDA_VISIBLE_DEVICES="$(nvisel -c 1 -f 10GiB)"
558
+ CUDA_VISIBLE_DEVICES="6,5,4,3,2,1,0"
559
+
560
+ # Use UUID strings in `CUDA_VISIBLE_DEVICES` environment variable
561
+ $ export CUDA_VISIBLE_DEVICES="$(nvisel -O uuid -c 2 -f 5000M)"
562
+ CUDA_VISIBLE_DEVICES="GPU-849d5a8d-610e-eeea-1fd4-81ff44a23794,GPU-18ef14e9-dec6-1d7e-1284-3010c6ce98b1,GPU-96de99c9-d68f-84c8-424c-7c75e59cc0a0,GPU-2428d171-8684-5b64-830c-435cd972ec4a,GPU-6d2a57c9-7783-44bb-9f53-13f36282830a,GPU-f8e5a624-2c7e-417c-e647-b764d26d4733,GPU-f9ca790e-683e-3d56-00ba-8f654e977e02"
563
+
564
+ # Pipe output to other shell utilities
565
+ $ nvisel --newline -O uuid -C 6 -f 8GiB
566
+ GPU-849d5a8d-610e-eeea-1fd4-81ff44a23794
567
+ GPU-18ef14e9-dec6-1d7e-1284-3010c6ce98b1
568
+ GPU-96de99c9-d68f-84c8-424c-7c75e59cc0a0
569
+ GPU-2428d171-8684-5b64-830c-435cd972ec4a
570
+ GPU-6d2a57c9-7783-44bb-9f53-13f36282830a
571
+ GPU-f8e5a624-2c7e-417c-e647-b764d26d4733
572
+ $ nvisel -0 -O uuid -c 2 -f 4GiB | xargs -0 -I {} nvidia-smi --id={} --query-gpu=index,memory.free --format=csv
573
+ CUDA_VISIBLE_DEVICES="GPU-849d5a8d-610e-eeea-1fd4-81ff44a23794,GPU-18ef14e9-dec6-1d7e-1284-3010c6ce98b1,GPU-96de99c9-d68f-84c8-424c-7c75e59cc0a0,GPU-2428d171-8684-5b64-830c-435cd972ec4a,GPU-6d2a57c9-7783-44bb-9f53-13f36282830a,GPU-f8e5a624-2c7e-417c-e647-b764d26d4733,GPU-f9ca790e-683e-3d56-00ba-8f654e977e02"
574
+ index, memory.free [MiB]
575
+ 6, 11018 MiB
576
+ index, memory.free [MiB]
577
+ 5, 11018 MiB
578
+ index, memory.free [MiB]
579
+ 4, 11018 MiB
580
+ index, memory.free [MiB]
581
+ 3, 11018 MiB
582
+ index, memory.free [MiB]
583
+ 2, 11018 MiB
584
+ index, memory.free [MiB]
585
+ 1, 11018 MiB
586
+ index, memory.free [MiB]
587
+ 0, 11018 MiB
588
+
589
+ # Normalize the `CUDA_VISIBLE_DEVICES` environment variable (e.g. convert UUIDs to indices or get full UUIDs for an abbreviated form)
590
+ $ nvisel -i "GPU-18ef14e9,GPU-849d5a8d" -S
591
+ 5,6
592
+ $ nvisel -i "GPU-18ef14e9,GPU-849d5a8d" -S -O uuid --newline
593
+ GPU-18ef14e9-dec6-1d7e-1284-3010c6ce98b1
594
+ GPU-849d5a8d-610e-eeea-1fd4-81ff44a23794
595
+ ```
596
+
597
+ You can also integrate `nvisel` into your training script like this:
598
+
599
+ ```python
600
+ # Put this at the top of the Python script
601
+ import os
602
+ from nvitop import select_devices
603
+
604
+ os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(
605
+ select_devices(format='uuid', min_count=4, min_free_memory='8GiB')
606
+ )
607
+ ```
608
+
609
+ Type `nvisel --help` for more command options:
610
+
611
+ ```text
612
+ usage: nvisel [--help] [--version]
613
+ [--inherit [CUDA_VISIBLE_DEVICES]] [--account-as-free [USERNAME ...]]
614
+ [--min-count N] [--max-count N] [--count N]
615
+ [--min-free-memory SIZE] [--min-total-memory SIZE]
616
+ [--max-gpu-utilization RATE] [--max-memory-utilization RATE]
617
+ [--tolerance TOL]
618
+ [--format FORMAT] [--sep SEP | --newline | --null] [--no-sort]
619
+
620
+ CUDA visible devices selection tool.
621
+
622
+ options:
623
+ --help, -h Show this help message and exit.
624
+ --version, -V Show nvisel's version number and exit.
625
+
626
+ constraints:
627
+ --inherit [CUDA_VISIBLE_DEVICES], -i [CUDA_VISIBLE_DEVICES]
628
+ Inherit the given `CUDA_VISIBLE_DEVICES`. If the argument is omitted, use the
629
+ value from the environment. This means selecting a subset of the currently
630
+ CUDA-visible devices.
631
+ --account-as-free [USERNAME ...]
632
+ Account the used GPU memory of the given users as free memory.
633
+ If this option is specified but without argument, `$USER` will be used.
634
+ --min-count N, -c N Minimum number of devices to select. (default: 0)
635
+ The tool will fail (exit non-zero) if the requested resource is not available.
636
+ --max-count N, -C N Maximum number of devices to select. (default: all devices)
637
+ --count N, -n N Overriding both `--min-count N` and `--max-count N`.
638
+ --min-free-memory SIZE, -f SIZE
639
+ Minimum free memory of devices to select. (example value: 4GiB)
640
+ If this constraint is given, check against all devices.
641
+ --min-total-memory SIZE, -t SIZE
642
+ Minimum total memory of devices to select. (example value: 10GiB)
643
+ If this constraint is given, check against all devices.
644
+ --max-gpu-utilization RATE, -G RATE
645
+ Maximum GPU utilization rate of devices to select. (example value: 30)
646
+ If this constraint is given, check against all devices.
647
+ --max-memory-utilization RATE, -M RATE
648
+ Maximum memory bandwidth utilization rate of devices to select. (example value: 50)
649
+ If this constraint is given, check against all devices.
650
+ --tolerance TOL, --tol TOL
651
+ The constraints tolerance (in percentage). (default: 0, i.e., strict)
652
+ This option can loose the constraints if the requested resource is not available.
653
+ For example, set `--tolerance=20` will accept a device with only 4GiB of free
654
+ memory when set `--min-free-memory=5GiB`.
655
+
656
+ formatting:
657
+ --format FORMAT, -O FORMAT
658
+ The output format of the selected device identifiers. (default: index)
659
+ If any MIG device found, the output format will be fallback to `uuid`.
660
+ --sep SEP, --separator SEP, -s SEP
661
+ Separator for the output. (default: ',')
662
+ --newline Use newline character as separator for the output, equivalent to `--sep=$'\n'`.
663
+ --null, -0 Use null character ('\x00') as separator for the output. This option corresponds
664
+ to the `-0` option of `xargs`.
665
+ --no-sort, -S Do not sort the device by memory usage and GPU utilization.
666
+ ```
667
+
668
+ ------
669
+
670
+ ### Callback Functions for Machine Learning Frameworks (DEPRECATED)
671
+
672
+ `nvitop` provides two builtin callbacks for [TensorFlow (Keras)](https://www.tensorflow.org) and [PyTorch Lightning](https://pytorchlightning.ai).
673
+
674
+ #### Callback for [TensorFlow (Keras)](https://www.tensorflow.org)
675
+
676
+ ```python
677
+ from tensorflow.python.keras.utils.multi_gpu_utils import multi_gpu_model
678
+ from tensorflow.python.keras.callbacks import TensorBoard
679
+ from nvitop.callbacks.keras import GpuStatsLogger
680
+ gpus = ['/gpu:0', '/gpu:1'] # or `gpus = [0, 1]` or `gpus = 2`
681
+ model = Xception(weights=None, ..)
682
+ model = multi_gpu_model(model, gpus) # optional
683
+ model.compile(..)
684
+ tb_callback = TensorBoard(log_dir='./logs') # or `keras.callbacks.CSVLogger`
685
+ gpu_stats = GpuStatsLogger(gpus)
686
+ model.fit(.., callbacks=[gpu_stats, tb_callback])
687
+ ```
688
+
689
+ **NOTE:** Users should assign a `keras.callbacks.TensorBoard` callback or a `keras.callbacks.CSVLogger` callback to the model. And the `GpuStatsLogger` callback should be placed before the `keras.callbacks.TensorBoard` / `keras.callbacks.CSVLogger` callback.
690
+
691
+ #### Callback for [PyTorch Lightning](https://lightning.ai)
692
+
693
+ ```python
694
+ from lightning.pytorch import Trainer
695
+ from nvitop.callbacks.lightning import GpuStatsLogger
696
+ gpu_stats = GpuStatsLogger()
697
+ trainer = Trainer(gpus=[..], logger=True, callbacks=[gpu_stats])
698
+ ```
699
+
700
+ **NOTE:** Users should assign a logger to the trainer.
701
+
702
+ #### [TensorBoard](https://github.com/tensorflow/tensorboard) Integration
703
+
704
+ Please refer to [Resource Metric Collector](#resource-metric-collector) for an example.
705
+
706
+ ------
707
+
708
+ ### More than a Monitor
709
+
710
+ `nvitop` can be easily integrated into other applications. You can use `nvitop` to make your own monitoring tools. The full API references host at <https://nvitop.readthedocs.io>.
711
+
712
+ #### Quick Start
713
+
714
+ A minimal script to monitor the GPU devices based on APIs from `nvitop`:
715
+
716
+ ```python
717
+ from nvitop import Device
718
+
719
+ devices = Device.all() # or `Device.cuda.all()` to use CUDA ordinal instead
720
+ for device in devices:
721
+ processes = device.processes() # type: Dict[int, GpuProcess]
722
+ sorted_pids = sorted(processes.keys())
723
+
724
+ print(device)
725
+ print(f' - Fan speed: {device.fan_speed()}%')
726
+ print(f' - Temperature: {device.temperature()}C')
727
+ print(f' - GPU utilization: {device.gpu_utilization()}%')
728
+ print(f' - Total memory: {device.memory_total_human()}')
729
+ print(f' - Used memory: {device.memory_used_human()}')
730
+ print(f' - Free memory: {device.memory_free_human()}')
731
+ print(f' - Processes ({len(processes)}): {sorted_pids}')
732
+ for pid in sorted_pids:
733
+ print(f' - {processes[pid]}')
734
+ print('-' * 120)
735
+ ```
736
+
737
+ Another more advanced approach with coloring:
738
+
739
+ ```python
740
+ import time
741
+
742
+ from nvitop import Device, GpuProcess, NA, colored
743
+
744
+ print(colored(time.strftime('%a %b %d %H:%M:%S %Y'), color='red', attrs=('bold',)))
745
+
746
+ devices = Device.cuda.all() # or `Device.all()` to use NVML ordinal instead
747
+ separator = False
748
+ for device in devices:
749
+ processes = device.processes() # type: Dict[int, GpuProcess]
750
+
751
+ print(colored(str(device), color='green', attrs=('bold',)))
752
+ print(colored(' - Fan speed: ', color='blue', attrs=('bold',)) + f'{device.fan_speed()}%')
753
+ print(colored(' - Temperature: ', color='blue', attrs=('bold',)) + f'{device.temperature()}C')
754
+ print(colored(' - GPU utilization: ', color='blue', attrs=('bold',)) + f'{device.gpu_utilization()}%')
755
+ print(colored(' - Total memory: ', color='blue', attrs=('bold',)) + f'{device.memory_total_human()}')
756
+ print(colored(' - Used memory: ', color='blue', attrs=('bold',)) + f'{device.memory_used_human()}')
757
+ print(colored(' - Free memory: ', color='blue', attrs=('bold',)) + f'{device.memory_free_human()}')
758
+ if len(processes) > 0:
759
+ processes = GpuProcess.take_snapshots(processes.values(), failsafe=True)
760
+ processes.sort(key=lambda process: (process.username, process.pid))
761
+
762
+ print(colored(f' - Processes ({len(processes)}):', color='blue', attrs=('bold',)))
763
+ fmt = ' {pid:<5} {username:<8} {cpu:>5} {host_memory:>8} {time:>8} {gpu_memory:>8} {sm:>3} {command:<}'.format
764
+ print(colored(fmt(pid='PID', username='USERNAME',
765
+ cpu='CPU%', host_memory='HOST-MEM', time='TIME',
766
+ gpu_memory='GPU-MEM', sm='SM%',
767
+ command='COMMAND'),
768
+ attrs=('bold',)))
769
+ for snapshot in processes:
770
+ print(fmt(pid=snapshot.pid,
771
+ username=snapshot.username[:7] + ('+' if len(snapshot.username) > 8 else snapshot.username[7:8]),
772
+ cpu=snapshot.cpu_percent, host_memory=snapshot.host_memory_human,
773
+ time=snapshot.running_time_human,
774
+ gpu_memory=(snapshot.gpu_memory_human if snapshot.gpu_memory_human is not NA else 'WDDM:N/A'),
775
+ sm=snapshot.gpu_sm_utilization,
776
+ command=snapshot.command))
777
+ else:
778
+ print(colored(' - No Running Processes', attrs=('bold',)))
779
+
780
+ if separator:
781
+ print('-' * 120)
782
+ separator = True
783
+ ```
784
+
785
+ <p align="center">
786
+ <img width="100%" src="https://user-images.githubusercontent.com/16078332/177041142-fe988d58-6a97-4559-84fd-b51204cf9231.png" alt="Demo">
787
+ <br/>
788
+ An example monitoring script built with APIs from <code>nvitop</code>.
789
+ </p>
790
+
791
+ ------
792
+
793
+ #### Status Snapshot
794
+
795
+ `nvitop` provides a helper function [`take_snapshots`](https://nvitop.readthedocs.io/en/latest/api/collector.html#nvitop.take_snapshots) to retrieve the status of both GPU devices and GPU processes at once. You can type `help(nvitop.take_snapshots)` in Python REPL for detailed documentation.
796
+
797
+ ```python
798
+ In [1]: from nvitop import take_snapshots, Device
799
+ ...: import os
800
+ ...: os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
801
+ ...: os.environ['CUDA_VISIBLE_DEVICES'] = '1,0' # comma-separated integers or UUID strings
802
+
803
+ In [2]: take_snapshots() # equivalent to `take_snapshots(Device.all())`
804
+ Out[2]:
805
+ SnapshotResult(
806
+ devices=[
807
+ DeviceSnapshot(
808
+ real=Device(index=0, ...),
809
+ ...
810
+ ),
811
+ ...
812
+ ],
813
+ gpu_processes=[
814
+ GpuProcessSnapshot(
815
+ real=GpuProcess(pid=xxxxxx, device=Device(index=0, ...), ...),
816
+ ...
817
+ ),
818
+ ...
819
+ ]
820
+ )
821
+
822
+ In [3]: device_snapshots, gpu_process_snapshots = take_snapshots(Device.all()) # type: Tuple[List[DeviceSnapshot], List[GpuProcessSnapshot]]
823
+
824
+ In [4]: device_snapshots, _ = take_snapshots(gpu_processes=False) # ignore process snapshots
825
+
826
+ In [5]: take_snapshots(Device.cuda.all()) # use CUDA device enumeration
827
+ Out[5]:
828
+ SnapshotResult(
829
+ devices=[
830
+ CudaDeviceSnapshot(
831
+ real=CudaDevice(cuda_index=0, nvml_index=1, ...),
832
+ ...
833
+ ),
834
+ CudaDeviceSnapshot(
835
+ real=CudaDevice(cuda_index=1, nvml_index=0, ...),
836
+ ...
837
+ ),
838
+ ],
839
+ gpu_processes=[
840
+ GpuProcessSnapshot(
841
+ real=GpuProcess(pid=xxxxxx, device=CudaDevice(cuda_index=0, ...), ...),
842
+ ...
843
+ ),
844
+ ...
845
+ ]
846
+ )
847
+
848
+ In [6]: take_snapshots(Device.cuda(1)) # <CUDA 1> only
849
+ Out[6]:
850
+ SnapshotResult(
851
+ devices=[
852
+ CudaDeviceSnapshot(
853
+ real=CudaDevice(cuda_index=1, nvml_index=0, ...),
854
+ ...
855
+ )
856
+ ],
857
+ gpu_processes=[
858
+ GpuProcessSnapshot(
859
+ real=GpuProcess(pid=xxxxxx, device=CudaDevice(cuda_index=1, ...), ...),
860
+ ...
861
+ ),
862
+ ...
863
+ ]
864
+ )
865
+ ```
866
+
867
+ Please refer to section [Low-level APIs](#low-level-apis) for more information.
868
+
869
+ ------
870
+
871
+ #### Resource Metric Collector
872
+
873
+ [`ResourceMetricCollector`](https://nvitop.readthedocs.io/en/latest/api/collector.html#nvitop.ResourceMetricCollector) is a class that collects resource metrics for host, GPUs and processes running on the GPUs. All metrics will be collected in an asynchronous manner. You can type `help(nvitop.ResourceMetricCollector)` in Python REPL for detailed documentation.
874
+
875
+ ```python
876
+ In [1]: from nvitop import ResourceMetricCollector, Device
877
+ ...: import os
878
+ ...: os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
879
+ ...: os.environ['CUDA_VISIBLE_DEVICES'] = '3,2,1,0' # comma-separated integers or UUID strings
880
+
881
+ In [2]: collector = ResourceMetricCollector() # log all devices and descendant processes of the current process on the GPUs
882
+ In [3]: collector = ResourceMetricCollector(root_pids={1}) # log all devices and all GPU processes
883
+ In [4]: collector = ResourceMetricCollector(devices=Device(0), root_pids={1}) # log <GPU 0> and all GPU processes on <GPU 0>
884
+ In [5]: collector = ResourceMetricCollector(devices=Device.cuda.all()) # use the CUDA ordinal
885
+
886
+ In [6]: with collector(tag='<tag>'):
887
+ ...: # Do something
888
+ ...: collector.collect() # -> Dict[str, float]
889
+ # key -> '<tag>/<scope>/<metric (unit)>/<mean/min/max>'
890
+ {
891
+ '<tag>/host/cpu_percent (%)/mean': 8.967849777683456,
892
+ '<tag>/host/cpu_percent (%)/min': 6.1,
893
+ '<tag>/host/cpu_percent (%)/max': 28.1,
894
+ ...,
895
+ '<tag>/host/memory_percent (%)/mean': 21.5,
896
+ '<tag>/host/swap_percent (%)/mean': 0.3,
897
+ '<tag>/host/memory_used (GiB)/mean': 91.0136418208109,
898
+ '<tag>/host/load_average (%) (1 min)/mean': 10.251427386878328,
899
+ '<tag>/host/load_average (%) (5 min)/mean': 10.072539414569503,
900
+ '<tag>/host/load_average (%) (15 min)/mean': 11.91126970422139,
901
+ ...,
902
+ '<tag>/cuda:0 (gpu:3)/memory_used (MiB)/mean': 3.875,
903
+ '<tag>/cuda:0 (gpu:3)/memory_free (MiB)/mean': 11015.562499999998,
904
+ '<tag>/cuda:0 (gpu:3)/memory_total (MiB)/mean': 11019.437500000002,
905
+ '<tag>/cuda:0 (gpu:3)/memory_percent (%)/mean': 0.0,
906
+ '<tag>/cuda:0 (gpu:3)/gpu_utilization (%)/mean': 0.0,
907
+ '<tag>/cuda:0 (gpu:3)/memory_utilization (%)/mean': 0.0,
908
+ '<tag>/cuda:0 (gpu:3)/fan_speed (%)/mean': 22.0,
909
+ '<tag>/cuda:0 (gpu:3)/temperature (C)/mean': 25.0,
910
+ '<tag>/cuda:0 (gpu:3)/power_usage (W)/mean': 19.11166264116916,
911
+ ...,
912
+ '<tag>/cuda:1 (gpu:2)/memory_used (MiB)/mean': 8878.875,
913
+ ...,
914
+ '<tag>/cuda:2 (gpu:1)/memory_used (MiB)/mean': 8182.875,
915
+ ...,
916
+ '<tag>/cuda:3 (gpu:0)/memory_used (MiB)/mean': 9286.875,
917
+ ...,
918
+ '<tag>/pid:12345/host/cpu_percent (%)/mean': 151.34342772112265,
919
+ '<tag>/pid:12345/host/host_memory (MiB)/mean': 44749.72373447514,
920
+ '<tag>/pid:12345/host/host_memory_percent (%)/mean': 8.675082352111717,
921
+ '<tag>/pid:12345/host/running_time (min)': 336.23803206741576,
922
+ '<tag>/pid:12345/cuda:1 (gpu:4)/gpu_memory (MiB)/mean': 8861.0,
923
+ '<tag>/pid:12345/cuda:1 (gpu:4)/gpu_memory_percent (%)/mean': 80.4,
924
+ '<tag>/pid:12345/cuda:1 (gpu:4)/gpu_memory_utilization (%)/mean': 6.711118172407917,
925
+ '<tag>/pid:12345/cuda:1 (gpu:4)/gpu_sm_utilization (%)/mean': 48.23283397736476,
926
+ ...,
927
+ '<tag>/duration (s)': 7.247399162035435,
928
+ '<tag>/timestamp': 1655909466.9981883
929
+ }
930
+ ```
931
+
932
+ The results can be easily logged into [TensorBoard](https://github.com/tensorflow/tensorboard) or a CSV file. For example:
933
+
934
+ ```python
935
+ import os
936
+
937
+ import torch
938
+ import torch.nn as nn
939
+ import torch.nn.functional as F
940
+ from torch.utils.tensorboard import SummaryWriter
941
+
942
+ from nvitop import CudaDevice, ResourceMetricCollector
943
+ from nvitop.callbacks.tensorboard import add_scalar_dict
944
+
945
+ # Build networks and prepare datasets
946
+ ...
947
+
948
+ # Logger and status collector
949
+ writer = SummaryWriter()
950
+ collector = ResourceMetricCollector(devices=CudaDevice.all(), # log all visible CUDA devices and use the CUDA ordinal
951
+ root_pids={os.getpid()}, # only log the descendant processes of the current process
952
+ interval=1.0) # snapshot interval for background daemon thread
953
+
954
+ # Start training
955
+ global_step = 0
956
+ for epoch in range(num_epoch):
957
+ with collector(tag='train'):
958
+ for batch in train_dataset:
959
+ with collector(tag='batch'):
960
+ metrics = train(net, batch)
961
+ global_step += 1
962
+ add_scalar_dict(writer, 'train', metrics, global_step=global_step)
963
+ add_scalar_dict(writer, 'resources', # tag='resources/train/batch/...'
964
+ collector.collect(),
965
+ global_step=global_step)
966
+
967
+ add_scalar_dict(writer, 'resources', # tag='resources/train/...'
968
+ collector.collect(),
969
+ global_step=epoch)
970
+
971
+ with collector(tag='validate'):
972
+ metrics = validate(net, validation_dataset)
973
+ add_scalar_dict(writer, 'validate', metrics, global_step=epoch)
974
+ add_scalar_dict(writer, 'resources', # tag='resources/validate/...'
975
+ collector.collect(),
976
+ global_step=epoch)
977
+ ```
978
+
979
+ Another example for logging into a CSV file:
980
+
981
+ ```python
982
+ import datetime
983
+ import time
984
+
985
+ import pandas as pd
986
+
987
+ from nvitop import ResourceMetricCollector
988
+
989
+ collector = ResourceMetricCollector(root_pids={1}, interval=2.0) # log all devices and all GPU processes
990
+ df = pd.DataFrame()
991
+
992
+ with collector(tag='resources'):
993
+ for _ in range(60):
994
+ # Do something
995
+ time.sleep(60)
996
+
997
+ metrics = collector.collect()
998
+ df_metrics = pd.DataFrame.from_records(metrics, index=[len(df)])
999
+ df = pd.concat([df, df_metrics], ignore_index=True)
1000
+ # Flush to CSV file ...
1001
+
1002
+ df.insert(0, 'time', df['resources/timestamp'].map(datetime.datetime.fromtimestamp))
1003
+ df.to_csv('results.csv', index=False)
1004
+ ```
1005
+
1006
+ You can also daemonize the collector in the background using [`collect_in_background`](https://nvitop.readthedocs.io/en/latest/api/collector.html#nvitop.collect_in_background) or [`ResourceMetricCollector.daemonize`](https://nvitop.readthedocs.io/en/latest/api/collector.html#nvitop.ResourceMetricCollector.daemonize) with callback functions.
1007
+
1008
+ ```python
1009
+ from nvitop import Device, ResourceMetricCollector, collect_in_background
1010
+
1011
+ logger = ...
1012
+
1013
+ def on_collect(metrics): # will be called periodically
1014
+ if logger.is_closed(): # closed manually by user
1015
+ return False
1016
+ logger.log(metrics)
1017
+ return True
1018
+
1019
+ def on_stop(collector): # will be called only once at stop
1020
+ if not logger.is_closed():
1021
+ logger.close() # cleanup
1022
+
1023
+ # Record metrics to the logger in the background every 5 seconds.
1024
+ # It will collect 5-second mean/min/max for each metric.
1025
+ collect_in_background(
1026
+ on_collect,
1027
+ ResourceMetricCollector(Device.cuda.all()),
1028
+ interval=5.0,
1029
+ on_stop=on_stop,
1030
+ )
1031
+ ```
1032
+
1033
+ or simply:
1034
+
1035
+ ```python
1036
+ ResourceMetricCollector(Device.cuda.all()).daemonize(
1037
+ on_collect,
1038
+ interval=5.0,
1039
+ on_stop=on_stop,
1040
+ )
1041
+ ```
1042
+
1043
+ ------
1044
+
1045
+ #### Low-level APIs
1046
+
1047
+ The full API references can be found at <https://nvitop.readthedocs.io>.
1048
+
1049
+ ##### Device
1050
+
1051
+ The [device module](https://nvitop.readthedocs.io/en/latest/api/device.html) provides:
1052
+
1053
+ <table class="autosummary longtable docutils align-default">
1054
+ <colgroup>
1055
+ <col style="width: 10%" />
1056
+ <col style="width: 90%" />
1057
+ </colgroup>
1058
+ <tbody>
1059
+ <tr class="row-odd">
1060
+ <td><p><a href="https://nvitop.readthedocs.io/en/latest/api/device.html#nvitop.Device" title="nvitop.Device"><code class="xref py py-obj docutils literal notranslate"><span class="pre">Device</span></code></a>([index, uuid, bus_id])</p></td>
1061
+ <td><p>Live class of the GPU devices, different from the device snapshots.</p></td>
1062
+ </tr>
1063
+ <tr class="row-even">
1064
+ <td><p><a href="https://nvitop.readthedocs.io/en/latest/api/device.html#nvitop.PhysicalDevice" title="nvitop.PhysicalDevice"><code class="xref py py-obj docutils literal notranslate"><span class="pre">PhysicalDevice</span></code></a>([index, uuid, bus_id])</p></td>
1065
+ <td><p>Class for physical devices.</p></td>
1066
+ </tr>
1067
+ <tr class="row-odd">
1068
+ <td><p><a href="https://nvitop.readthedocs.io/en/latest/api/device.html#nvitop.MigDevice" title="nvitop.MigDevice"><code class="xref py py-obj docutils literal notranslate"><span class="pre">MigDevice</span></code></a>([index, uuid, bus_id])</p></td>
1069
+ <td><p>Class for MIG devices.</p></td>
1070
+ </tr>
1071
+ <tr class="row-even">
1072
+ <td><p><a href="https://nvitop.readthedocs.io/en/latest/api/device.html#nvitop.CudaDevice" title="nvitop.CudaDevice"><code class="xref py py-obj docutils literal notranslate"><span class="pre">CudaDevice</span></code></a>([cuda_index, nvml_index, uuid])</p></td>
1073
+ <td><p>Class for devices enumerated over the CUDA ordinal.</p></td>
1074
+ </tr>
1075
+ <tr class="row-odd">
1076
+ <td><p><a href="https://nvitop.readthedocs.io/en/latest/api/device.html#nvitop.CudaMigDevice" title="nvitop.CudaMigDevice"><code class="xref py py-obj docutils literal notranslate"><span class="pre">CudaMigDevice</span></code></a>([cuda_index, nvml_index, uuid])</p></td>
1077
+ <td><p>Class for CUDA devices that are MIG devices.</p></td>
1078
+ </tr>
1079
+ <tr class="row-even">
1080
+ <td><p><a href="https://nvitop.readthedocs.io/en/latest/api/device.html#nvitop.parse_cuda_visible_devices" title="nvitop.parse_cuda_visible_devices"><code class="xref py py-obj docutils literal notranslate"><span class="pre">parse_cuda_visible_devices</span></code></a>([...])</p></td>
1081
+ <td><p>Parse the given <code class="docutils literal notranslate"><span class="pre">CUDA_VISIBLE_DEVICES</span></code> value into a list of NVML device indices.</p></td>
1082
+ </tr>
1083
+ <tr class="row-odd">
1084
+ <td><p><a href="https://nvitop.readthedocs.io/en/latest/api/device.html#nvitop.normalize_cuda_visible_devices" title="nvitop.normalize_cuda_visible_devices"><code class="xref py py-obj docutils literal notranslate"><span class="pre">normalize_cuda_visible_devices</span></code></a>([...])</p></td>
1085
+ <td><p>Parse the given <code class="docutils literal notranslate"><span class="pre">CUDA_VISIBLE_DEVICES</span></code> value and convert it into a comma-separated string of UUIDs.</p></td>
1086
+ </tr>
1087
+ </tbody>
1088
+ </table>
1089
+
1090
+ ```python
1091
+ In [1]: from nvitop import (
1092
+ ...: host,
1093
+ ...: Device, PhysicalDevice, CudaDevice,
1094
+ ...: parse_cuda_visible_devices, normalize_cuda_visible_devices
1095
+ ...: HostProcess, GpuProcess,
1096
+ ...: NA,
1097
+ ...: )
1098
+ ...: import os
1099
+ ...: os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
1100
+ ...: os.environ['CUDA_VISIBLE_DEVICES'] = '9,8,7,6' # comma-separated integers or UUID strings
1101
+
1102
+ In [2]: Device.driver_version()
1103
+ Out[2]: '525.60.11'
1104
+
1105
+ In [3]: Device.cuda_driver_version() # the maximum CUDA version supported by the driver (can be different from the CUDA Runtime version)
1106
+ Out[3]: '12.0'
1107
+
1108
+ In [4]: Device.cuda_runtime_version() # the CUDA Runtime version
1109
+ Out[4]: '11.8'
1110
+
1111
+ In [5]: Device.count()
1112
+ Out[5]: 10
1113
+
1114
+ In [6]: CudaDevice.count() # or `Device.cuda.count()`
1115
+ Out[6]: 4
1116
+
1117
+ In [7]: all_devices = Device.all() # all devices on board (physical device)
1118
+ ...: nvidia0, nvidia1 = Device.from_indices([0, 1]) # from physical device indices
1119
+ ...: all_devices
1120
+ Out[7]: [
1121
+ PhysicalDevice(index=0, name="GeForce RTX 2080 Ti", total_memory=11019MiB),
1122
+ PhysicalDevice(index=1, name="GeForce RTX 2080 Ti", total_memory=11019MiB),
1123
+ PhysicalDevice(index=2, name="GeForce RTX 2080 Ti", total_memory=11019MiB),
1124
+ PhysicalDevice(index=3, name="GeForce RTX 2080 Ti", total_memory=11019MiB),
1125
+ PhysicalDevice(index=4, name="GeForce RTX 2080 Ti", total_memory=11019MiB),
1126
+ PhysicalDevice(index=5, name="GeForce RTX 2080 Ti", total_memory=11019MiB),
1127
+ PhysicalDevice(index=6, name="GeForce RTX 2080 Ti", total_memory=11019MiB),
1128
+ PhysicalDevice(index=7, name="GeForce RTX 2080 Ti", total_memory=11019MiB),
1129
+ PhysicalDevice(index=8, name="GeForce RTX 2080 Ti", total_memory=11019MiB),
1130
+ PhysicalDevice(index=9, name="GeForce RTX 2080 Ti", total_memory=11019MiB)
1131
+ ]
1132
+
1133
+ In [8]: # NOTE: The function results might be different between calls when the `CUDA_VISIBLE_DEVICES` environment variable has been modified
1134
+ ...: cuda_visible_devices = Device.from_cuda_visible_devices() # from the `CUDA_VISIBLE_DEVICES` environment variable
1135
+ ...: cuda0, cuda1 = Device.from_cuda_indices([0, 1]) # from CUDA device indices (might be different from physical device indices if `CUDA_VISIBLE_DEVICES` is set)
1136
+ ...: cuda_visible_devices = CudaDevice.all() # shortcut to `Device.from_cuda_visible_devices()`
1137
+ ...: cuda_visible_devices = Device.cuda.all() # `Device.cuda` is aliased to `CudaDevice`
1138
+ ...: cuda_visible_devices
1139
+ Out[8]: [
1140
+ CudaDevice(cuda_index=0, nvml_index=9, name="NVIDIA GeForce RTX 2080 Ti", total_memory=11019MiB),
1141
+ CudaDevice(cuda_index=1, nvml_index=8, name="NVIDIA GeForce RTX 2080 Ti", total_memory=11019MiB),
1142
+ CudaDevice(cuda_index=2, nvml_index=7, name="NVIDIA GeForce RTX 2080 Ti", total_memory=11019MiB),
1143
+ CudaDevice(cuda_index=3, nvml_index=6, name="NVIDIA GeForce RTX 2080 Ti", total_memory=11019MiB)
1144
+ ]
1145
+
1146
+ In [9]: nvidia0 = Device(0) # from device index (or `Device(index=0)`)
1147
+ ...: nvidia0
1148
+ Out[9]: PhysicalDevice(index=0, name="GeForce RTX 2080 Ti", total_memory=11019MiB)
1149
+
1150
+ In [10]: nvidia1 = Device(uuid='GPU-01234567-89ab-cdef-0123-456789abcdef') # from UUID string (or just `Device('GPU-xxxxxxxx-...')`)
1151
+ ...: nvidia2 = Device(bus_id='00000000:06:00.0') # from PCI bus ID
1152
+ ...: nvidia1
1153
+ Out[10]: PhysicalDevice(index=1, name="GeForce RTX 2080 Ti", total_memory=11019MiB)
1154
+
1155
+ In [11]: cuda0 = CudaDevice(0) # from CUDA device index (equivalent to `CudaDevice(cuda_index=0)`)
1156
+ ...: cuda1 = CudaDevice(nvml_index=8) # from physical device index
1157
+ ...: cuda3 = CudaDevice(uuid='GPU-xxxxxxxx-...') # from UUID string
1158
+ ...: cuda4 = Device.cuda(4) # `Device.cuda` is aliased to `CudaDevice`
1159
+ ...: cuda0
1160
+ Out[11]:
1161
+ CudaDevice(cuda_index=0, nvml_index=9, name="NVIDIA GeForce RTX 2080 Ti", total_memory=11019MiB)
1162
+
1163
+ In [12]: nvidia0.memory_used() # in bytes
1164
+ Out[12]: 9293398016
1165
+
1166
+ In [13]: nvidia0.memory_used_human()
1167
+ Out[13]: '8862MiB'
1168
+
1169
+ In [14]: nvidia0.gpu_utilization() # in percentage
1170
+ Out[14]: 5
1171
+
1172
+ In [15]: nvidia0.processes() # type: Dict[int, GpuProcess]
1173
+ Out[15]: {
1174
+ 52059: GpuProcess(pid=52059, gpu_memory=7885MiB, type=C, device=PhysicalDevice(index=0, name="GeForce RTX 2080 Ti", total_memory=11019MiB), host=HostProcess(pid=52059, name='ipython3', status='sleeping', started='14:31:22')),
1175
+ 53002: GpuProcess(pid=53002, gpu_memory=967MiB, type=C, device=PhysicalDevice(index=0, name="GeForce RTX 2080 Ti", total_memory=11019MiB), host=HostProcess(pid=53002, name='python', status='running', started='14:31:59'))
1176
+ }
1177
+
1178
+ In [16]: nvidia1_snapshot = nvidia1.as_snapshot()
1179
+ ...: nvidia1_snapshot
1180
+ Out[16]: PhysicalDeviceSnapshot(
1181
+ real=PhysicalDevice(index=1, name="GeForce RTX 2080 Ti", total_memory=11019MiB),
1182
+ bus_id='00000000:05:00.0',
1183
+ compute_mode='Default',
1184
+ clock_infos=ClockInfos(graphics=1815, sm=1815, memory=6800, video=1680), # in MHz
1185
+ clock_speed_infos=ClockSpeedInfos(current=ClockInfos(graphics=1815, sm=1815, memory=6800, video=1680), max=ClockInfos(graphics=2100, sm=2100, memory=7000, video=1950)), # in MHz
1186
+ cuda_compute_capability=(7, 5),
1187
+ current_driver_model='N/A',
1188
+ decoder_utilization=0, # in percentage
1189
+ display_active='Disabled',
1190
+ display_mode='Disabled',
1191
+ encoder_utilization=0, # in percentage
1192
+ fan_speed=22, # in percentage
1193
+ gpu_utilization=17, # in percentage (NOTE: this is the utilization rate of SMs, i.e. GPU percent)
1194
+ index=1,
1195
+ max_clock_infos=ClockInfos(graphics=2100, sm=2100, memory=7000, video=1950), # in MHz
1196
+ memory_clock=6800, # in MHz
1197
+ memory_free=10462232576, # in bytes
1198
+ memory_free_human='9977MiB',
1199
+ memory_info=MemoryInfo(total=11554717696, free=10462232576, used=1092485120) # in bytes
1200
+ memory_percent=9.5, # in percentage (NOTE: this is the percentage of used GPU memory)
1201
+ memory_total=11554717696, # in bytes
1202
+ memory_total_human='11019MiB',
1203
+ memory_usage='1041MiB / 11019MiB',
1204
+ memory_used=1092485120, # in bytes
1205
+ memory_used_human='1041MiB',
1206
+ memory_utilization=7, # in percentage (NOTE: this is the utilization rate of GPU memory bandwidth)
1207
+ mig_mode='N/A',
1208
+ name='GeForce RTX 2080 Ti',
1209
+ pcie_rx_throughput=1000, # in KiB/s
1210
+ pcie_rx_throughput_human='1000KiB/s',
1211
+ pcie_throughput=ThroughputInfo(tx=1000, rx=1000), # in KiB/s
1212
+ pcie_tx_throughput=1000, # in KiB/s
1213
+ pcie_tx_throughput_human='1000KiB/s',
1214
+ performance_state='P2',
1215
+ persistence_mode='Disabled',
1216
+ power_limit=250000, # in milliwatts (mW)
1217
+ power_status='66W / 250W', # in watts (W)
1218
+ power_usage=66051, # in milliwatts (mW)
1219
+ sm_clock=1815, # in MHz
1220
+ temperature=39, # in Celsius
1221
+ total_volatile_uncorrected_ecc_errors='N/A',
1222
+ utilization_rates=UtilizationRates(gpu=17, memory=7, encoder=0, decoder=0), # in percentage
1223
+ uuid='GPU-01234567-89ab-cdef-0123-456789abcdef',
1224
+ )
1225
+
1226
+ In [17]: nvidia1_snapshot.memory_percent # snapshot uses properties instead of function calls
1227
+ Out[17]: 9.5
1228
+
1229
+ In [18]: nvidia1_snapshot['memory_info'] # snapshot also supports `__getitem__` by string
1230
+ Out[18]: MemoryInfo(total=11554717696, free=10462232576, used=1092485120)
1231
+
1232
+ In [19]: nvidia1_snapshot.bar1_memory_info # snapshot will automatically retrieve not presented attributes from `real`
1233
+ Out[19]: MemoryInfo(total=268435456, free=257622016, used=10813440)
1234
+ ```
1235
+
1236
+ **NOTE:** Some entry values may be `'N/A'` (type: [`NaType`](https://nvitop.readthedocs.io/en/latest/index.html#nvitop.NaType), a subclass of `str`) when the corresponding resources are not applicable. The [`NA`](https://nvitop.readthedocs.io/en/latest/index.html#nvitop.NA) value supports arithmetic operations. It acts like `math.nan: float`.
1237
+
1238
+ ```python
1239
+ >>> from nvitop import NA
1240
+ >>> NA
1241
+ 'N/A'
1242
+
1243
+ >>> 'memory usage: {}'.format(NA) # NA is an instance of `str`
1244
+ 'memory usage: N/A'
1245
+ >>> NA.lower() # NA is an instance of `str`
1246
+ 'n/a'
1247
+ >>> NA.ljust(5) # NA is an instance of `str`
1248
+ 'N/A '
1249
+ >>> NA + 'str' # string contamination if the operand is a string
1250
+ 'N/Astr'
1251
+
1252
+ >>> float(NA) # explicit conversion to float (`math.nan`)
1253
+ nan
1254
+ >>> NA + 1 # auto-casting to float if the operand is a number
1255
+ nan
1256
+ >>> NA * 1024 # auto-casting to float if the operand is a number
1257
+ nan
1258
+ >>> NA / (1024 * 1024) # auto-casting to float if the operand is a number
1259
+ nan
1260
+ ```
1261
+
1262
+ You can use `entry != 'N/A'` conditions to avoid exceptions. It's safe to use `float(entry)` for numbers while `NaType` will be converted to `math.nan`. For example:
1263
+
1264
+ ```python
1265
+ memory_used: Union[int, NaType] = device.memory_used() # memory usage in bytes or `'N/A'`
1266
+ memory_used_in_mib: float = float(memory_used) / (1 << 20) # memory usage in Mebibytes (MiB) or `math.nan`
1267
+ ```
1268
+
1269
+ It's safe to compare `NaType` with numbers, but `NaType` is always larger than any number:
1270
+
1271
+ ```python
1272
+ devices_by_used_memory = sorted(Device.all(), key=Device.memory_used, reverse=True) # it's safe to compare `'N/A'` with numbers
1273
+ devices_by_free_memory = sorted(Device.all(), key=Device.memory_free, reverse=True) # please add `memory_free != 'N/A'` checks if sort in descending order here
1274
+ ```
1275
+
1276
+ See [`nvitop.NaType`](https://nvitop.readthedocs.io/en/latest/apis/index.html#nvitop.NaType) documentation for more details.
1277
+
1278
+ ##### Process
1279
+
1280
+ The [process module](https://nvitop.readthedocs.io/en/latest/api/process.html) provides:
1281
+
1282
+ <table class="autosummary longtable docutils align-default">
1283
+ <colgroup>
1284
+ <col style="width: 10%" />
1285
+ <col style="width: 90%" />
1286
+ </colgroup>
1287
+ <tbody>
1288
+ <tr class="row-odd">
1289
+ <td><p><a href="https://nvitop.readthedocs.io/en/latest/api/process.html#nvitop.HostProcess" title="nvitop.HostProcess"><code class="xref py py-obj docutils literal notranslate"><span class="pre">HostProcess</span></code></a>([pid])</p></td>
1290
+ <td><p>Represents an OS process with the given PID.</p></td>
1291
+ </tr>
1292
+ <tr class="row-even">
1293
+ <td><p><a href="https://nvitop.readthedocs.io/en/latest/api/process.html#nvitop.GpuProcess" title="nvitop.GpuProcess"><code class="xref py py-obj docutils literal notranslate"><span class="pre">GpuProcess</span></code></a>(pid, device[, gpu_memory, ...])</p></td>
1294
+ <td><p>Represents a process with the given PID running on the given GPU device.</p></td>
1295
+ </tr>
1296
+ <tr class="row-odd">
1297
+ <td><p><a href="https://nvitop.readthedocs.io/en/latest/api/process.html#nvitop.command_join" title="nvitop.command_join"><code class="xref py py-obj docutils literal notranslate"><span class="pre">command_join</span></code></a>(cmdline)</p></td>
1298
+ <td><p>Returns a shell-escaped string from command line arguments.</p></td>
1299
+ </tr>
1300
+ </tbody>
1301
+ </table>
1302
+
1303
+ ```python
1304
+ In [20]: processes = nvidia1.processes() # type: Dict[int, GpuProcess]
1305
+ ...: processes
1306
+ Out[20]: {
1307
+ 23266: GpuProcess(pid=23266, gpu_memory=1031MiB, type=C, device=Device(index=1, name="GeForce RTX 2080 Ti", total_memory=11019MiB), host=HostProcess(pid=23266, name='python3', status='running', started='2021-05-10 21:02:40'))
1308
+ }
1309
+
1310
+ In [21]: process = processes[23266]
1311
+ ...: process
1312
+ Out[21]: GpuProcess(pid=23266, gpu_memory=1031MiB, type=C, device=Device(index=1, name="GeForce RTX 2080 Ti", total_memory=11019MiB), host=HostProcess(pid=23266, name='python3', status='running', started='2021-05-10 21:02:40'))
1313
+
1314
+ In [22]: process.status() # GpuProcess will automatically inherit attributes from GpuProcess.host
1315
+ Out[22]: 'running'
1316
+
1317
+ In [23]: process.cmdline() # type: List[str]
1318
+ Out[23]: ['python3', 'rllib_train.py']
1319
+
1320
+ In [24]: process.command() # type: str
1321
+ Out[24]: 'python3 rllib_train.py'
1322
+
1323
+ In [25]: process.cwd() # GpuProcess will automatically inherit attributes from GpuProcess.host
1324
+ Out[25]: '/home/xxxxxx/Projects/xxxxxx'
1325
+
1326
+ In [26]: process.gpu_memory_human()
1327
+ Out[26]: '1031MiB'
1328
+
1329
+ In [27]: process.as_snapshot()
1330
+ Out[27]: GpuProcessSnapshot(
1331
+ real=GpuProcess(pid=23266, gpu_memory=1031MiB, type=C, device=PhysicalDevice(index=1, name="GeForce RTX 2080 Ti", total_memory=11019MiB), host=HostProcess(pid=23266, name='python3', status='running', started='2021-05-10 21:02:40')),
1332
+ cmdline=['python3', 'rllib_train.py'],
1333
+ command='python3 rllib_train.py',
1334
+ compute_instance_id='N/A',
1335
+ cpu_percent=98.5, # in percentage
1336
+ device=PhysicalDevice(index=1, name="GeForce RTX 2080 Ti", total_memory=11019MiB),
1337
+ gpu_encoder_utilization=0, # in percentage
1338
+ gpu_decoder_utilization=0, # in percentage
1339
+ gpu_instance_id='N/A',
1340
+ gpu_memory=1081081856, # in bytes
1341
+ gpu_memory_human='1031MiB',
1342
+ gpu_memory_percent=9.4, # in percentage (NOTE: this is the percentage of used GPU memory)
1343
+ gpu_memory_utilization=5, # in percentage (NOTE: this is the utilization rate of GPU memory bandwidth)
1344
+ gpu_sm_utilization=0, # in percentage (NOTE: this is the utilization rate of SMs, i.e. GPU percent)
1345
+ host=HostProcessSnapshot(
1346
+ real=HostProcess(pid=23266, name='python3', status='running', started='2021-05-10 21:02:40'),
1347
+ cmdline=['python3', 'rllib_train.py'],
1348
+ command='python3 rllib_train.py',
1349
+ cpu_percent=98.5, # in percentage
1350
+ host_memory=9113627439, # in bytes
1351
+ host_memory_human='8691MiB',
1352
+ is_running=True,
1353
+ memory_percent=1.6849018430285683, # in percentage
1354
+ name='python3',
1355
+ running_time=datetime.timedelta(days=1, seconds=80013, microseconds=470024),
1356
+ running_time_human='46:13:33',
1357
+ running_time_in_seconds=166413.470024,
1358
+ status='running',
1359
+ username='panxuehai',
1360
+ ),
1361
+ host_memory=9113627439, # in bytes
1362
+ host_memory_human='8691MiB',
1363
+ is_running=True,
1364
+ memory_percent=1.6849018430285683, # in percentage (NOTE: this is the percentage of used host memory)
1365
+ name='python3',
1366
+ pid=23266,
1367
+ running_time=datetime.timedelta(days=1, seconds=80013, microseconds=470024),
1368
+ running_time_human='46:13:33',
1369
+ running_time_in_seconds=166413.470024,
1370
+ status='running',
1371
+ type='C', # 'C' for Compute / 'G' for Graphics / 'C+G' for Both
1372
+ username='panxuehai',
1373
+ )
1374
+
1375
+ In [28]: process.uids() # GpuProcess will automatically inherit attributes from GpuProcess.host
1376
+ Out[28]: puids(real=1001, effective=1001, saved=1001)
1377
+
1378
+ In [29]: process.kill() # GpuProcess will automatically inherit attributes from GpuProcess.host
1379
+
1380
+ In [30]: list(map(Device.processes, all_devices)) # all processes
1381
+ Out[30]: [
1382
+ {
1383
+ 52059: GpuProcess(pid=52059, gpu_memory=7885MiB, type=C, device=PhysicalDevice(index=0, name="GeForce RTX 2080 Ti", total_memory=11019MiB), host=HostProcess(pid=52059, name='ipython3', status='sleeping', started='14:31:22')),
1384
+ 53002: GpuProcess(pid=53002, gpu_memory=967MiB, type=C, device=PhysicalDevice(index=0, name="GeForce RTX 2080 Ti", total_memory=11019MiB), host=HostProcess(pid=53002, name='python', status='running', started='14:31:59'))
1385
+ },
1386
+ {},
1387
+ {},
1388
+ {},
1389
+ {},
1390
+ {},
1391
+ {},
1392
+ {},
1393
+ {
1394
+ 84748: GpuProcess(pid=84748, gpu_memory=8975MiB, type=C, device=PhysicalDevice(index=8, name="GeForce RTX 2080 Ti", total_memory=11019MiB), host=HostProcess(pid=84748, name='python', status='running', started='11:13:38'))
1395
+ },
1396
+ {
1397
+ 84748: GpuProcess(pid=84748, gpu_memory=8341MiB, type=C, device=PhysicalDevice(index=9, name="GeForce RTX 2080 Ti", total_memory=11019MiB), host=HostProcess(pid=84748, name='python', status='running', started='11:13:38'))
1398
+ }
1399
+ ]
1400
+
1401
+ In [31]: this = HostProcess(os.getpid())
1402
+ ...: this
1403
+ Out[31]: HostProcess(pid=35783, name='python', status='running', started='19:19:00')
1404
+
1405
+ In [32]: this.cmdline() # type: List[str]
1406
+ Out[32]: ['python', '-c', 'import IPython; IPython.terminal.ipapp.launch_new_instance()']
1407
+
1408
+ In [33]: this.command() # not simply `' '.join(cmdline)` but quotes are added
1409
+ Out[33]: 'python -c "import IPython; IPython.terminal.ipapp.launch_new_instance()"'
1410
+
1411
+ In [34]: this.memory_info()
1412
+ Out[34]: pmem(rss=83988480, vms=343543808, shared=12079104, text=8192, lib=0, data=297435136, dirty=0)
1413
+
1414
+ In [35]: import cupy as cp
1415
+ ...: x = cp.zeros((10000, 1000))
1416
+ ...: this = GpuProcess(os.getpid(), cuda0) # construct from `GpuProcess(pid, device)` explicitly rather than calling `device.processes()`
1417
+ ...: this
1418
+ Out[35]: GpuProcess(pid=35783, gpu_memory=N/A, type=N/A, device=CudaDevice(cuda_index=0, nvml_index=9, name="NVIDIA GeForce RTX 2080 Ti", total_memory=11019MiB), host=HostProcess(pid=35783, name='python', status='running', started='19:19:00'))
1419
+
1420
+ In [36]: this.update_gpu_status() # update used GPU memory from new driver queries
1421
+ Out[36]: 267386880
1422
+
1423
+ In [37]: this
1424
+ Out[37]: GpuProcess(pid=35783, gpu_memory=255MiB, type=C, device=CudaDevice(cuda_index=0, nvml_index=9, name="NVIDIA GeForce RTX 2080 Ti", total_memory=11019MiB), host=HostProcess(pid=35783, name='python', status='running', started='19:19:00'))
1425
+
1426
+ In [38]: id(this) == id(GpuProcess(os.getpid(), cuda0)) # IMPORTANT: the instance will be reused while the process is running
1427
+ Out[38]: True
1428
+ ```
1429
+
1430
+ ##### Host (inherited from [psutil](https://github.com/giampaolo/psutil))
1431
+
1432
+ ```python
1433
+ In [39]: host.cpu_count()
1434
+ Out[39]: 88
1435
+
1436
+ In [40]: host.cpu_percent()
1437
+ Out[40]: 18.5
1438
+
1439
+ In [41]: host.cpu_times()
1440
+ Out[41]: scputimes(user=2346377.62, nice=53321.44, system=579177.52, idle=10323719.85, iowait=28750.22, irq=0.0, softirq=11566.87, steal=0.0, guest=0.0, guest_nice=0.0)
1441
+
1442
+ In [42]: host.load_average()
1443
+ Out[42]: (14.88, 17.8, 19.91)
1444
+
1445
+ In [43]: host.virtual_memory()
1446
+ Out[43]: svmem(total=270352478208, available=192275968000, percent=28.9, used=53350518784, free=88924037120, active=125081112576, inactive=44803993600, buffers=37006450688, cached=91071471616, shared=23820632064, slab=8200687616)
1447
+
1448
+ In [44]: host.memory_percent()
1449
+ Out[44]: 28.9
1450
+
1451
+ In [45]: host.swap_memory()
1452
+ Out[45]: sswap(total=65534947328, used=475136, free=65534472192, percent=0.0, sin=2404139008, sout=4259434496)
1453
+
1454
+ In [46]: host.swap_percent()
1455
+ Out[46]: 0.0
1456
+ ```
1457
+
1458
+ ------
1459
+
1460
+ ## Screenshots
1461
+
1462
+ ![Screen Recording](https://user-images.githubusercontent.com/16078332/113173772-508dc380-927c-11eb-84c5-b6f496e54c08.gif)
1463
+
1464
+ Example output of `nvitop -1`:
1465
+
1466
+ <p align="center">
1467
+ <img width="100%" src="https://user-images.githubusercontent.com/16078332/117765250-41793880-b260-11eb-8a1b-9c32868a46d4.png" alt="Screenshot">
1468
+ </p>
1469
+
1470
+ Example output of `nvitop`:
1471
+
1472
+ <table>
1473
+ <tr valign="center" align="center">
1474
+ <td>Full</td>
1475
+ <td>Compact</td>
1476
+ </tr>
1477
+ <tr valign="top" align="center">
1478
+ <td><img src="https://user-images.githubusercontent.com/16078332/117765260-4342fc00-b260-11eb-9198-7bcfdd1db113.png" alt="Full"></td>
1479
+ <td><img src="https://user-images.githubusercontent.com/16078332/117765274-476f1980-b260-11eb-9afd-877cca54e0bc.png" alt="Compact"></td>
1480
+ </tr>
1481
+ </table>
1482
+
1483
+ Tree-view screen (shortcut: <kbd>t</kbd>) for GPU processes and their ancestors:
1484
+
1485
+ <p align="center">
1486
+ <img width="100%" src="https://user-images.githubusercontent.com/16078332/123914889-7b3e0400-d9b2-11eb-9b71-a48971617c2a.png" alt="Tree-view">
1487
+ </p>
1488
+
1489
+ **NOTE:** The process tree is built in backward order (recursively back to the tree root). Only GPU processes along with their children and ancestors (parents and grandparents ...) will be shown. Not all running processes will be displayed.
1490
+
1491
+ Environment variable screen (shortcut: <kbd>e</kbd>):
1492
+
1493
+ <p align="center">
1494
+ <img width="100%" src="https://user-images.githubusercontent.com/16078332/123914881-7a0cd700-d9b2-11eb-8da1-26f7a3a7c2b6.png" alt="Environment Screen">
1495
+ </p>
1496
+
1497
+ Spectrum-like bar charts (with option <code>--colorful</code>):
1498
+
1499
+ <p align="center">
1500
+ <img width="100%" src="https://user-images.githubusercontent.com/16078332/182555606-8388e5a5-43a9-4990-90d4-46e45ac448a0.png" alt="Spectrum-like Bar Charts">
1501
+ <br/>
1502
+ </p>
1503
+
1504
+ ------
1505
+
1506
+ ## Changelog
1507
+
1508
+ See [CHANGELOG.md](https://github.com/XuehaiPan/nvitop/blob/HEAD/CHANGELOG.md).
1509
+
1510
+ ------
1511
+
1512
+ ## License
1513
+
1514
+ The source code of `nvitop` is dual-licensed by the **Apache License, Version 2.0 (Apache-2.0)** and **GNU General Public License, Version 3 (GPL-3.0)**. The `nvitop` CLI is released under the **GPL-3.0** license while the remaining part of `nvitop` is released under the **Apache-2.0** license. The license files can be found at [LICENSE](https://github.com/XuehaiPan/nvitop/blob/HEAD/LICENSE) (Apache-2.0) and [COPYING](https://github.com/XuehaiPan/nvitop/blob/HEAD/COPYING) (GPL-3.0).
1515
+
1516
+ The source code is organized as:
1517
+
1518
+ ```text
1519
+ nvitop (GPL-3.0)
1520
+ ├── __init__.py (Apache-2.0)
1521
+ ├── version.py (Apache-2.0)
1522
+ ├── api (Apache-2.0)
1523
+ │ ├── LICENSE (Apache-2.0)
1524
+ │ └── * (Apache-2.0)
1525
+ ├── callbacks (Apache-2.0)
1526
+ │ ├── LICENSE (Apache-2.0)
1527
+ │ └── * (Apache-2.0)
1528
+ ├── select.py (Apache-2.0)
1529
+ ├── __main__.py (GPL-3.0)
1530
+ ├── cli.py (GPL-3.0)
1531
+ └── tui (GPL-3.0)
1532
+ ├── COPYING (GPL-3.0)
1533
+ └── * (GPL-3.0)
1534
+ ```
1535
+
1536
+ ### Copyright Notice
1537
+
1538
+ Please feel free to use `nvitop` as a dependency for your own projects. The following Python import statements are permitted:
1539
+
1540
+ ```python
1541
+ import nvitop
1542
+ import nvitop as alias
1543
+ import nvitop.api as api
1544
+ import nvitop.device as device
1545
+ from nvitop import *
1546
+ from nvitop.api import *
1547
+ from nvitop import Device, ResourceMetricCollector
1548
+ ```
1549
+
1550
+ The public APIs from `nvitop` are released under the **Apache License, Version 2.0 (Apache-2.0)**. The original license files can be found at [LICENSE](https://github.com/XuehaiPan/nvitop/blob/HEAD/LICENSE), [nvitop/api/LICENSE](https://github.com/XuehaiPan/nvitop/blob/HEAD/nvitop/api/LICENSE), and [nvitop/callbacks/LICENSE](https://github.com/XuehaiPan/nvitop/blob/HEAD/nvitop/callbacks/LICENSE).
1551
+
1552
+ The CLI of `nvitop` is released under the **GNU General Public License, Version 3 (GPL-3.0)**. The original license files can be found at [COPYING](https://github.com/XuehaiPan/nvitop/blob/HEAD/COPYING) and [nvitop/tui/COPYING](https://github.com/XuehaiPan/nvitop/blob/HEAD/nvitop/tui/COPYING). If you dynamically load the source code of `nvitop`'s CLI or TUI:
1553
+
1554
+ ```python
1555
+ from nvitop import cli
1556
+ from nvitop import tui
1557
+ import nvitop.cli
1558
+ import nvitop.tui
1559
+ ```
1560
+
1561
+ your source code should also be released under the GPL-3.0 License.
1562
+
1563
+ If you want to add or modify some features of `nvitop`'s CLI, or copy some source code of `nvitop`'s CLI into your own code, the source code should also be released under the GPL-3.0 License (as `nvitop` contains some modified source code from [ranger](https://github.com/ranger/ranger) under the GPL-3.0 License).
.venv/lib/python3.10/site-packages/nvitop-1.5.3.dist-info/RECORD ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ../../../bin/nvisel,sha256=ijf-8eGUm2wgR1maKbrxzD5WVVw-VtMBnKCNVavcBTc,314
2
+ ../../../bin/nvitop,sha256=5tYRS4cLpLo36crEEXW-Llw8yoRcdbk6KzerjwKQrPM,311
3
+ nvitop-1.5.3.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
4
+ nvitop-1.5.3.dist-info/METADATA,sha256=Fh-tBdjUVl1M04EPLULbh5lf4i8NuaNA6dgHSprVsjE,78404
5
+ nvitop-1.5.3.dist-info/RECORD,,
6
+ nvitop-1.5.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ nvitop-1.5.3.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
8
+ nvitop-1.5.3.dist-info/entry_points.txt,sha256=KapUQUNeukBIt7kA6TzIPYMZHco_zud1vK0lMXqX2Fo,71
9
+ nvitop-1.5.3.dist-info/licenses/COPYING,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
10
+ nvitop-1.5.3.dist-info/licenses/LICENSE,sha256=SopLLKbMm5DzDYZ1wSDfYFuT1l0GObAHfOAUFqZ3bTg,11368
11
+ nvitop-1.5.3.dist-info/top_level.txt,sha256=XdSN8bn0PccqPEltMgjbA9zh2r7CLNJjzL5bjZYUGgQ,7
12
+ nvitop/__init__.py,sha256=Xl75rKpSQmZqq9err_QhlSQlg09I46D8Q2J4XgLfTwo,1668
13
+ nvitop/__main__.py,sha256=ADFld7mUiHEQQDqxCyL8NP8_ZtVrddzeb-aVOCh7-bE,245
14
+ nvitop/api/__init__.py,sha256=sJkqDqD60__dvuRIJ2bD2XsuAvNdh0HY8Ow_qLH7Gc4,2666
15
+ nvitop/api/caching.py,sha256=avMtj8kDSuErcTAqP9m5jPl0aQHZVUg-1JyM0V6U1LE,10146
16
+ nvitop/api/collector.py,sha256=7f6MH-BLPHk0zNx9lNgYHF5oncRtaHtSD-gRcU4VkPE,35465
17
+ nvitop/api/device.py,sha256=pCt7U7w8s_AC59QxuGBfHeEhWiyn2pLGMNIjVG6tU4A,138669
18
+ nvitop/api/host.py,sha256=YA69pvp-mMZ1hZ4Vyl54vrxY-kcPVxh9iUkiNFinTiA,4065
19
+ nvitop/api/libcuda.py,sha256=aKt5hNOTFq9_BtOmjvu6UvVv2dbvtIFGD3O_DZBQMuc,38588
20
+ nvitop/api/libcudart.py,sha256=z_sKG9BUQTHHDdytZE_UwC0KPWweHqoCuoum5rPdYpk,43834
21
+ nvitop/api/libnvml.py,sha256=OJ_XGRGz9TsGXSe0Io15ezWjix6pt1YbuAYF3JGjYV4,43066
22
+ nvitop/api/process.py,sha256=HxBzEAynpIhEih7yjEiXZxEyrpKnaexMAOuQ5jHOWkQ,40734
23
+ nvitop/api/termcolor.py,sha256=s89ze2_E6EVVGPnN1nvYYfgOroXi8eATQ7nsotoNeIs,7856
24
+ nvitop/api/utils.py,sha256=Ttm3wNvC2iIQoa0hNLK09zoCH3RVWoHlhLGHTImjrxM,24572
25
+ nvitop/callbacks/__init__.py,sha256=HyQOo_3qgEq3Lpl5WvSo0ihsBFIhwzNOQH1QRaiuoLY,1051
26
+ nvitop/callbacks/keras.py,sha256=SEOBEF2pFS-985Y1TgVgpNb6MbbusmOEM0fP9-HFNGY,7974
27
+ nvitop/callbacks/lightning.py,sha256=1cVWo9XgYk-XN8B1E7w6TEwkfHhkk1zGay1LSjsQv1w,8202
28
+ nvitop/callbacks/pytorch_lightning.py,sha256=Za2lllm5XkZtTYa8v3_t-Tm5bLsAn7-eIgJNAtGzvzI,8375
29
+ nvitop/callbacks/tensorboard.py,sha256=-s5i0kW-SNihGhKNdMAvJj3dzNkFd7fJqFqRRA623cM,1863
30
+ nvitop/callbacks/utils.py,sha256=dmTkZ53ux7CRPseTV7ApQ26LzZ0g2kTC_ruka2mWIaI,2604
31
+ nvitop/cli.py,sha256=HQdfLQnXdwbKa4ddQA0AnYcHyKbRuP_6JnJVVhtz858,14586
32
+ nvitop/select.py,sha256=Y7-p-Y_S9-ZGR8ffZJRElKnTdxO2e9ggATINCIDFap8,20542
33
+ nvitop/tui/__init__.py,sha256=tOYq1itOiBwI7OIePpzkTwNxe8u-DNf3AsdyJBMk8CM,470
34
+ nvitop/tui/library/__init__.py,sha256=u_RafwW2SESGgDRwimv1W9PDJeKuhBW7RW3EaDllnOQ,2057
35
+ nvitop/tui/library/device.py,sha256=PwBf4IPEn7kjEJEWNC2IUZD4fQEnBXqbmQL8fZEo5C8,8221
36
+ nvitop/tui/library/displayable.py,sha256=WnVaYT9lQqth6oaP0U_W3BZV-bpnPo0aBGaHMG91iME,9289
37
+ nvitop/tui/library/history.py,sha256=pQx4o2SrM7gpGvdRtIovd3XwkYdkrSUIt5PaXULowIY,14235
38
+ nvitop/tui/library/host.py,sha256=sVJMCKXM3_4ZSYQjDw3yUZfoZl7nkO0VdP6dBSHk7SA,2972
39
+ nvitop/tui/library/keybinding.py,sha256=iPX23vOPcjoVl-m1qhJVPVJDeOBgpNB_sXNj9PWZE9E,13883
40
+ nvitop/tui/library/libcurses.py,sha256=wxIo5lP_q30oyjBd1jYYGq07ZTsyBZKwDvcS9XnJ0WQ,10227
41
+ nvitop/tui/library/messagebox.py,sha256=cOfAHmv56cSIr3zByWuuF1qw2ZFgsxEridqRFjdHOAQ,14732
42
+ nvitop/tui/library/mouse.py,sha256=4BUXxFeZn1twmftJdNZuDFf7E_L6SnV_8QZmRsrJE3A,3872
43
+ nvitop/tui/library/process.py,sha256=036Ta3d8uq-CyBV9pZVZaQ1HlIAvPmnJOGOrkYfpBEg,3950
44
+ nvitop/tui/library/selection.py,sha256=QPDhg3v6-TVV8QWfUP9cY0vpBhQAb1HU4OZsA1dsOlQ,6030
45
+ nvitop/tui/library/utils.py,sha256=UvOXUX23udEkO-msyhcDat6ttkMu6EMdHA71kfv42Tc,3334
46
+ nvitop/tui/library/widestring.py,sha256=LycasKh39MulefL-BUFQWZmcIF46qPe-zM1jrHrlp4I,7818
47
+ nvitop/tui/screens/__init__.py,sha256=2mIOd9IRjPNEXy1w-USy67Kb7jGVgyFpIfoEBi6Kf_8,677
48
+ nvitop/tui/screens/base.py,sha256=L9IgtgA5uLMF3Cnl5hsjwWA-bTOU-okfscLJYbsGIJc,651
49
+ nvitop/tui/screens/environ.py,sha256=E1bxcoQpMNpvrvS6QwKbXgaQbrfK32jwcWKS2e3T5qs,9404
50
+ nvitop/tui/screens/help.py,sha256=jgEOGCQlGDmdbNUQ2hM62TcB9x7O245_jWBdJmn1VPM,4947
51
+ nvitop/tui/screens/main/__init__.py,sha256=P0lYBIrb4yXsjpL-OXZBXN62UAycUaY8DQAZ7-AiodI,11586
52
+ nvitop/tui/screens/main/panels/__init__.py,sha256=wmP_jqBsnagZc3wfuR1hpZ7bDHEQq8W9wpc6RAuidhQ,556
53
+ nvitop/tui/screens/main/panels/base.py,sha256=WBpvCwC2rSazIW5YjGRY72aT4jMtA_EUo4MEkawFi6M,729
54
+ nvitop/tui/screens/main/panels/device.py,sha256=dsayJsbM6GBZLYsZ9j5puOAj0N_KPuvIinWkwvQJ3bU,23123
55
+ nvitop/tui/screens/main/panels/host.py,sha256=JPnqe_I7KNajmbsQe3H2J6vJuI7XhF2TEZZsg_I7dz4,17784
56
+ nvitop/tui/screens/main/panels/process.py,sha256=aYbzN43Oi-2VwALDv8usyx5pW0NuEgFyDQLxBvwPKVs,28327
57
+ nvitop/tui/screens/metrics.py,sha256=-bgTPqAjv00HJiq0mKCfSA2JrGigiuUbt7zvQ0j04U4,24082
58
+ nvitop/tui/screens/treeview.py,sha256=Vr8cQGVbNU2JjJXr62Ma-LOb8U9OEW_7RqLzGZTYJdY,22552
59
+ nvitop/tui/tui.py,sha256=xB68ceFNt9IGfEg-2ePyPIaBY-mjsQidjPNby-SNfbY,13849
60
+ nvitop/version.py,sha256=qo2i0gZ5DfW1hp5HbF0U35Qp3Cg5ukCByIfO7xifCCg,4297
.venv/lib/python3.10/site-packages/nvitop-1.5.3.dist-info/REQUESTED ADDED
File without changes
.venv/lib/python3.10/site-packages/nvitop-1.5.3.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
.venv/lib/python3.10/site-packages/nvitop-1.5.3.dist-info/entry_points.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [console_scripts]
2
+ nvisel = nvitop.select:main
3
+ nvitop = nvitop.cli:main
.venv/lib/python3.10/site-packages/nvitop-1.5.3.dist-info/licenses/COPYING ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
.venv/lib/python3.10/site-packages/nvitop-1.5.3.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2021-2025 Xuehai Pan. All Rights Reserved.
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
.venv/lib/python3.10/site-packages/nvitop-1.5.3.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ nvitop
.venv/lib/python3.10/site-packages/nvitop/__init__.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is part of nvitop, the interactive NVIDIA-GPU process viewer.
2
+ #
3
+ # Copyright 2021-2025 Xuehai Pan. All Rights Reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ # ==============================================================================
17
+ """An interactive NVIDIA-GPU process viewer and beyond, the one-stop solution for GPU process management."""
18
+
19
+ import sys
20
+
21
+ from nvitop import api
22
+ from nvitop.api import * # noqa: F403
23
+ from nvitop.api import (
24
+ caching,
25
+ collector,
26
+ device,
27
+ host,
28
+ libcuda,
29
+ libcudart,
30
+ libnvml,
31
+ process,
32
+ termcolor,
33
+ utils,
34
+ )
35
+ from nvitop.select import select_devices
36
+ from nvitop.version import __version__
37
+
38
+
39
+ __all__ = [*api.__all__, 'select_devices']
40
+
41
+ # Add submodules to the top-level namespace
42
+ for submodule in (
43
+ caching,
44
+ collector,
45
+ device,
46
+ host,
47
+ libcuda,
48
+ libcudart,
49
+ libnvml,
50
+ process,
51
+ termcolor,
52
+ utils,
53
+ ):
54
+ sys.modules[f'{__name__}.{submodule.__name__.rpartition(".")[-1]}'] = submodule
55
+
56
+ # Remove the nvitop.select module from sys.modules
57
+ # Required for `python -m nvitop.select` to work properly
58
+ sys.modules.pop(f'{__name__}.select', None)
59
+
60
+ del sys
.venv/lib/python3.10/site-packages/nvitop/__main__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is part of nvitop, the interactive NVIDIA-GPU process viewer.
2
+ # License: GNU GPL version 3.
3
+
4
+ """The interactive NVIDIA-GPU process viewer."""
5
+
6
+ import sys
7
+
8
+ from nvitop.cli import main
9
+
10
+
11
+ if __name__ == '__main__':
12
+ sys.exit(main())
.venv/lib/python3.10/site-packages/nvitop/api/__init__.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is part of nvitop, the interactive NVIDIA-GPU process viewer.
2
+ #
3
+ # Copyright 2021-2025 Xuehai Pan. All Rights Reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ # ==============================================================================
17
+ """The core APIs of nvitop."""
18
+
19
+ from nvitop.api import (
20
+ caching,
21
+ collector,
22
+ device,
23
+ host,
24
+ libcuda,
25
+ libcudart,
26
+ libnvml,
27
+ process,
28
+ termcolor,
29
+ utils,
30
+ )
31
+ from nvitop.api.caching import ttl_cache
32
+ from nvitop.api.collector import ResourceMetricCollector, collect_in_background, take_snapshots
33
+ from nvitop.api.device import (
34
+ CudaDevice,
35
+ CudaMigDevice,
36
+ Device,
37
+ MigDevice,
38
+ PhysicalDevice,
39
+ normalize_cuda_visible_devices,
40
+ parse_cuda_visible_devices,
41
+ )
42
+ from nvitop.api.libnvml import NVMLError, nvmlCheckReturn
43
+ from nvitop.api.process import GpuProcess, HostProcess, command_join
44
+ from nvitop.api.utils import ( # explicitly export these to appease mypy
45
+ NA,
46
+ SIZE_UNITS,
47
+ UINT_MAX,
48
+ ULONGLONG_MAX,
49
+ GiB,
50
+ KiB,
51
+ MiB,
52
+ NaType,
53
+ NotApplicable,
54
+ NotApplicableType,
55
+ PiB,
56
+ Snapshot,
57
+ TiB,
58
+ boolify,
59
+ bytes2human,
60
+ colored,
61
+ human2bytes,
62
+ set_color,
63
+ timedelta2human,
64
+ utilization2string,
65
+ )
66
+
67
+
68
+ __all__ = [ # noqa: RUF022
69
+ 'NVMLError',
70
+ 'nvmlCheckReturn',
71
+ 'libnvml',
72
+ 'libcuda',
73
+ 'libcudart',
74
+ # nvitop.api.device
75
+ 'Device',
76
+ 'PhysicalDevice',
77
+ 'MigDevice',
78
+ 'CudaDevice',
79
+ 'CudaMigDevice',
80
+ 'parse_cuda_visible_devices',
81
+ 'normalize_cuda_visible_devices',
82
+ # nvitop.api.process
83
+ 'host',
84
+ 'HostProcess',
85
+ 'GpuProcess',
86
+ 'command_join',
87
+ # nvitop.api.collector
88
+ 'take_snapshots',
89
+ 'collect_in_background',
90
+ 'ResourceMetricCollector',
91
+ # nvitop.api.caching
92
+ 'ttl_cache',
93
+ # nvitop.api.utils
94
+ 'NA',
95
+ 'NaType',
96
+ 'NotApplicable',
97
+ 'NotApplicableType',
98
+ 'UINT_MAX',
99
+ 'ULONGLONG_MAX',
100
+ 'KiB',
101
+ 'MiB',
102
+ 'GiB',
103
+ 'TiB',
104
+ 'PiB',
105
+ 'SIZE_UNITS',
106
+ 'bytes2human',
107
+ 'human2bytes',
108
+ 'timedelta2human',
109
+ 'utilization2string',
110
+ 'colored',
111
+ 'set_color',
112
+ 'boolify',
113
+ 'Snapshot',
114
+ ]
.venv/lib/python3.10/site-packages/nvitop/api/caching.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is part of nvitop, the interactive NVIDIA-GPU process viewer.
2
+ #
3
+ # Copyright 2021-2025 Xuehai Pan. All Rights Reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ # ==============================================================================
17
+ """Caching utilities."""
18
+
19
+ from __future__ import annotations
20
+
21
+ import builtins
22
+ import functools
23
+ import time
24
+ from dataclasses import dataclass
25
+ from threading import RLock
26
+ from typing import TYPE_CHECKING, Any, NamedTuple, overload
27
+
28
+
29
+ if TYPE_CHECKING:
30
+ from collections.abc import Callable, Hashable, Sized
31
+ from collections.abc import Set as AbstractSet
32
+ from typing import TypeVar
33
+ from typing_extensions import (
34
+ ParamSpec, # Python 3.10+
35
+ Self, # Python 3.11+
36
+ )
37
+
38
+ _P = ParamSpec('_P')
39
+ _T = TypeVar('_T')
40
+
41
+
42
+ __all__ = ['ttl_cache']
43
+
44
+
45
+ class _CacheInfo(NamedTuple):
46
+ """A named tuple representing the cache statistics."""
47
+
48
+ hits: int
49
+ misses: int
50
+ maxsize: int
51
+ currsize: int
52
+
53
+
54
+ try:
55
+ from functools import _make_key
56
+ except ImportError:
57
+
58
+ class _HashedSeq(list):
59
+ """This class guarantees that hash() will be called no more than once per element."""
60
+
61
+ __slots__ = ('__hashvalue',)
62
+
63
+ def __init__(
64
+ self,
65
+ seq: tuple[Any, ...],
66
+ hash: Callable[[Any], int] = builtins.hash, # pylint: disable=redefined-builtin
67
+ ) -> None:
68
+ """Initialize the hashed sequence."""
69
+ self[:] = seq
70
+ self.__hashvalue = hash(seq)
71
+
72
+ def __hash__(self) -> int: # type: ignore[override]
73
+ """Return the hash value of the hashed sequence."""
74
+ return self.__hashvalue
75
+
76
+ _KWD_MARK = object()
77
+
78
+ # pylint: disable-next=too-many-arguments
79
+ def _make_key( # type: ignore[misc]
80
+ args: tuple[Hashable, ...],
81
+ kwds: dict[str, Hashable],
82
+ typed: bool,
83
+ *,
84
+ kwd_mark: tuple[object, ...] = (_KWD_MARK,),
85
+ fasttypes: AbstractSet[type] = frozenset({int, str}),
86
+ tuple: type[tuple] = builtins.tuple, # pylint: disable=redefined-builtin
87
+ type: type[type] = builtins.type, # pylint: disable=redefined-builtin
88
+ len: Callable[[Sized], int] = builtins.len, # pylint: disable=redefined-builtin
89
+ ) -> Hashable:
90
+ """Make a cache key from optionally typed positional and keyword arguments."""
91
+ key = args
92
+ if kwds:
93
+ key += kwd_mark
94
+ for item in kwds.items():
95
+ key += item
96
+ if typed:
97
+ key += tuple(type(v) for v in args)
98
+ if kwds:
99
+ key += tuple(type(v) for v in kwds.values())
100
+ elif len(key) == 1 and type(key[0]) in fasttypes:
101
+ return key[0]
102
+ return _HashedSeq(key)
103
+
104
+
105
+ @dataclass
106
+ class _TTLCacheLink: # pylint: disable=too-few-public-methods
107
+ __slots__ = ('expires', 'key', 'next', 'prev', 'value')
108
+
109
+ prev: Self
110
+ next: Self # pylint: disable=redefined-builtin
111
+ key: Hashable
112
+ value: Any
113
+ expires: float
114
+
115
+
116
+ @overload
117
+ def ttl_cache(
118
+ maxsize: int | None = 128,
119
+ *,
120
+ ttl: float = 600.0,
121
+ timer: Callable[[], float] = time.monotonic,
122
+ typed: bool = False,
123
+ ) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: ...
124
+
125
+
126
+ @overload
127
+ def ttl_cache(
128
+ maxsize: Callable[_P, _T],
129
+ *,
130
+ ttl: float = 600.0,
131
+ timer: Callable[[], float] = time.monotonic,
132
+ typed: bool = False,
133
+ ) -> Callable[_P, _T]: ...
134
+
135
+
136
+ # pylint: disable-next=too-many-statements
137
+ def ttl_cache(
138
+ maxsize: int | Callable[_P, _T] | None = 128,
139
+ *,
140
+ ttl: float = 600.0,
141
+ timer: Callable[[], float] = time.monotonic,
142
+ typed: bool = False,
143
+ ) -> Callable[[Callable[_P, _T]], Callable[_P, _T]] | Callable[_P, _T]:
144
+ """Time aware cache decorator."""
145
+ if isinstance(maxsize, int):
146
+ # Negative maxsize is treated as 0
147
+ maxsize = max(0, maxsize)
148
+ elif callable(maxsize) and isinstance(typed, bool):
149
+ # The user_function was passed in directly via the maxsize argument
150
+ func, maxsize = maxsize, 128
151
+ return ttl_cache(maxsize, ttl=ttl, timer=timer, typed=typed)(func)
152
+ elif maxsize is not None:
153
+ raise TypeError('Expected first argument to be an integer, a callable, or None')
154
+
155
+ if ttl < 0.0:
156
+ raise ValueError('TTL must be a non-negative number')
157
+ if not callable(timer):
158
+ raise TypeError('Timer must be a callable')
159
+
160
+ if maxsize == 0 or maxsize is None:
161
+ return functools.lru_cache(maxsize=maxsize, typed=typed) # type: ignore[return-value]
162
+
163
+ # pylint: disable-next=too-many-statements,too-many-locals
164
+ def wrapper(func: Callable[_P, _T], /) -> Callable[_P, _T]:
165
+ cache: dict[Any, _TTLCacheLink] = {}
166
+ cache_get = cache.get # bound method to lookup a key or return None
167
+ cache_len = cache.__len__ # get cache size without calling len()
168
+ lock = RLock() # because linked-list updates aren't thread-safe
169
+ # root of the circular doubly linked list
170
+ root = _TTLCacheLink(*((None,) * 5)) # type: ignore[arg-type]
171
+ root.prev = root.next = root # initialize by pointing to self
172
+ hits = misses = 0
173
+ full = False
174
+
175
+ def unlink(link: _TTLCacheLink) -> _TTLCacheLink:
176
+ with lock:
177
+ link_prev, link_next = link.prev, link.next
178
+ link_next.prev, link_prev.next = link_prev, link_next
179
+ return link_next
180
+
181
+ def append(link: _TTLCacheLink) -> _TTLCacheLink:
182
+ with lock:
183
+ last = root.prev
184
+ last.next = root.prev = link
185
+ link.prev, link.next = last, root
186
+ return link
187
+
188
+ def move_to_end(link: _TTLCacheLink) -> _TTLCacheLink:
189
+ with lock:
190
+ unlink(link)
191
+ append(link)
192
+ return link
193
+
194
+ def expire() -> None:
195
+ nonlocal full
196
+
197
+ with lock:
198
+ now = timer()
199
+ front = root.next
200
+ while front is not root and front.expires < now:
201
+ del cache[front.key]
202
+ front = unlink(front)
203
+ full = cache_len() >= maxsize
204
+
205
+ @functools.wraps(func)
206
+ def wrapped(*args: _P.args, **kwargs: _P.kwargs) -> _T:
207
+ # Size limited time aware caching
208
+ nonlocal root, hits, misses, full
209
+
210
+ key = _make_key(args, kwargs, typed)
211
+ with lock:
212
+ link = cache_get(key)
213
+ if link is not None:
214
+ if timer() < link.expires:
215
+ hits += 1
216
+ return link.value
217
+ expire()
218
+
219
+ misses += 1
220
+ result = func(*args, **kwargs)
221
+ expires = timer() + ttl
222
+ with lock:
223
+ if key in cache:
224
+ # Getting here means that this same key was added to the cache while the lock
225
+ # was released or the key was expired. Move the link to the front of the
226
+ # circular queue.
227
+ link = move_to_end(cache[key])
228
+ # We need only update the expiration time.
229
+ link.value = result
230
+ link.expires = expires
231
+ else:
232
+ if full:
233
+ expire()
234
+ if full:
235
+ # Use the old root to store the new key and result.
236
+ root.key = key
237
+ root.value = result
238
+ root.expires = expires
239
+ # Empty the oldest link and make it the new root.
240
+ # Keep a reference to the old key and old result to prevent their ref counts
241
+ # from going to zero during the update. That will prevent potentially
242
+ # arbitrary object clean-up code (i.e. __del__) from running while we're
243
+ # still adjusting the links.
244
+ front = root.next
245
+ old_key = front.key
246
+ front.key = front.value = front.expires = None # type: ignore[assignment]
247
+ # Now update the cache dictionary.
248
+ del cache[old_key]
249
+ # Save the potentially reentrant cache[key] assignment for last, after the
250
+ # root and links have been put in a consistent state.
251
+ cache[key], root = root, front
252
+ else:
253
+ # Put result in a new link at the front of the queue.
254
+ cache[key] = append(_TTLCacheLink(None, None, key, result, expires)) # type: ignore[arg-type]
255
+ full = cache_len() >= maxsize
256
+ return result
257
+
258
+ def cache_info() -> _CacheInfo:
259
+ """Report cache statistics."""
260
+ with lock:
261
+ expire()
262
+ return _CacheInfo(hits, misses, maxsize, cache_len())
263
+
264
+ def cache_clear() -> None:
265
+ """Clear the cache and cache statistics."""
266
+ nonlocal hits, misses, full
267
+ with lock:
268
+ cache.clear()
269
+ root.prev = root.next = root
270
+ root.key = root.value = root.expires = None # type: ignore[assignment]
271
+ hits = misses = 0
272
+ full = False
273
+
274
+ wrapped.cache_info = cache_info # type: ignore[attr-defined]
275
+ wrapped.cache_clear = cache_clear # type: ignore[attr-defined]
276
+ wrapped.cache_parameters = lambda: {'maxsize': maxsize, 'typed': typed} # type: ignore[attr-defined]
277
+ return wrapped
278
+
279
+ return wrapper
.venv/lib/python3.10/site-packages/nvitop/api/collector.py ADDED
@@ -0,0 +1,912 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is part of nvitop, the interactive NVIDIA-GPU process viewer.
2
+ #
3
+ # Copyright 2021-2025 Xuehai Pan. All Rights Reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ # ==============================================================================
17
+ """Resource metrics collectors."""
18
+
19
+ from __future__ import annotations
20
+
21
+ import contextlib
22
+ import itertools
23
+ import math
24
+ import os
25
+ import threading
26
+ import time
27
+ from collections import OrderedDict, defaultdict
28
+ from typing import TYPE_CHECKING, ClassVar, NamedTuple, TypeVar
29
+ from weakref import WeakSet
30
+
31
+ from nvitop.api import host
32
+ from nvitop.api.device import CudaDevice, Device
33
+ from nvitop.api.process import GpuProcess, HostProcess
34
+ from nvitop.api.utils import GiB, MiB, Snapshot
35
+
36
+
37
+ if TYPE_CHECKING:
38
+ from collections.abc import Callable, Generator, Iterable
39
+
40
+
41
+ __all__ = ['ResourceMetricCollector', 'collect_in_background', 'take_snapshots']
42
+
43
+
44
+ class SnapshotResult(NamedTuple): # pylint: disable=missing-class-docstring
45
+ devices: list[Snapshot]
46
+ gpu_processes: list[Snapshot]
47
+
48
+
49
+ timer = time.monotonic
50
+
51
+
52
+ _T = TypeVar('_T')
53
+
54
+
55
+ def _unique(iterable: Iterable[_T], /) -> list[_T]:
56
+ return list(OrderedDict.fromkeys(iterable).keys())
57
+
58
+
59
+ # pylint: disable-next=too-many-branches
60
+ def take_snapshots(
61
+ devices: Device | Iterable[Device] | None = None,
62
+ *,
63
+ gpu_processes: bool | GpuProcess | Iterable[GpuProcess] | None = None,
64
+ ) -> SnapshotResult:
65
+ """Retrieve status of demanded devices and GPU processes.
66
+
67
+ Args:
68
+ devices (Optional[Union[Device, Iterable[Device]]]):
69
+ Requested devices for snapshots. If not given, the devices will be determined from GPU
70
+ processes: **(1)** All devices (no GPU processes are given); **(2)** Devices that used
71
+ by given GPU processes.
72
+ gpu_processes (Optional[Union[bool, GpuProcess, Iterable[GpuProcess]]]):
73
+ Requested GPU processes snapshots. If not given, all GPU processes running on the
74
+ requested device will be returned. The GPU process snapshots can be suppressed by
75
+ specifying ``gpu_processes=False``.
76
+
77
+ Returns: SnapshotResult
78
+ A named tuple containing two lists of snapshots.
79
+
80
+ Note:
81
+ If not arguments are specified, all devices and all GPU processes will
82
+ be returned.
83
+
84
+ Examples:
85
+ >>> from nvitop import take_snapshots, Device
86
+ >>> import os
87
+ >>> os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
88
+ >>> os.environ['CUDA_VISIBLE_DEVICES'] = '1,0'
89
+
90
+ >>> take_snapshots() # equivalent to `take_snapshots(Device.all())`
91
+ SnapshotResult(
92
+ devices=[
93
+ PhysicalDeviceSnapshot(
94
+ real=PhysicalDevice(index=0, ...),
95
+ ...
96
+ ),
97
+ ...
98
+ ],
99
+ gpu_processes=[
100
+ GpuProcessSnapshot(
101
+ real=GpuProcess(pid=xxxxxx, device=PhysicalDevice(index=0, ...), ...),
102
+ ...
103
+ ),
104
+ ...
105
+ ]
106
+ )
107
+
108
+ >>> device_snapshots, gpu_process_snapshots = take_snapshots(Device.all()) # type: Tuple[List[DeviceSnapshot], List[GpuProcessSnapshot]]
109
+
110
+ >>> device_snapshots, _ = take_snapshots(gpu_processes=False) # ignore process snapshots
111
+
112
+ >>> take_snapshots(Device.cuda.all()) # use CUDA device enumeration
113
+ SnapshotResult(
114
+ devices=[
115
+ CudaDeviceSnapshot(
116
+ real=CudaDevice(cuda_index=0, physical_index=1, ...),
117
+ ...
118
+ ),
119
+ CudaDeviceSnapshot(
120
+ real=CudaDevice(cuda_index=1, physical_index=0, ...),
121
+ ...
122
+ ),
123
+ ],
124
+ gpu_processes=[
125
+ GpuProcessSnapshot(
126
+ real=GpuProcess(pid=xxxxxx, device=CudaDevice(cuda_index=0, ...), ...),
127
+ ...
128
+ ),
129
+ ...
130
+ ]
131
+ )
132
+
133
+ >>> take_snapshots(Device.cuda(1)) # <CUDA 1> only
134
+ SnapshotResult(
135
+ devices=[
136
+ CudaDeviceSnapshot(
137
+ real=CudaDevice(cuda_index=1, physical_index=0, ...),
138
+ ...
139
+ )
140
+ ],
141
+ gpu_processes=[
142
+ GpuProcessSnapshot(
143
+ real=GpuProcess(pid=xxxxxx, device=CudaDevice(cuda_index=1, ...), ...),
144
+ ...
145
+ ),
146
+ ...
147
+ ]
148
+ )
149
+ """ # pylint: disable=line-too-long
150
+ if isinstance(devices, Device):
151
+ devices = [devices]
152
+ if isinstance(gpu_processes, GpuProcess):
153
+ gpu_processes = [gpu_processes]
154
+
155
+ if gpu_processes is not None and gpu_processes is not True:
156
+ if gpu_processes: # is a non-empty list/tuple
157
+ gpu_processes = list(gpu_processes)
158
+ process_devices = _unique(process.device for process in gpu_processes)
159
+ for device in process_devices:
160
+ device.processes() # update GPU status for requested GPU processes
161
+ if devices is None:
162
+ devices = process_devices
163
+ else:
164
+ gpu_processes = [] # False or empty list/tuple
165
+ if devices is None:
166
+ devices = Device.all()
167
+ else:
168
+ if devices is None:
169
+ physical_devices = Device.all()
170
+ devices = []
171
+ leaf_devices: list[Device] = []
172
+ for physical_device in physical_devices:
173
+ devices.append(physical_device)
174
+ mig_devices = physical_device.mig_devices()
175
+ if len(mig_devices) > 0:
176
+ devices.extend(mig_devices)
177
+ leaf_devices.extend(mig_devices)
178
+ else:
179
+ leaf_devices.append(physical_device)
180
+ else:
181
+ leaf_devices = devices = list(devices)
182
+ gpu_processes = list(
183
+ itertools.chain.from_iterable(device.processes().values() for device in leaf_devices),
184
+ )
185
+
186
+ devices = [device.as_snapshot() for device in devices] # type: ignore[union-attr]
187
+ gpu_processes = GpuProcess.take_snapshots(gpu_processes, failsafe=True)
188
+
189
+ return SnapshotResult(devices, gpu_processes)
190
+
191
+
192
+ # pylint: disable-next=too-many-arguments
193
+ def collect_in_background(
194
+ on_collect: Callable[[dict[str, float]], bool],
195
+ collector: ResourceMetricCollector | None = None,
196
+ interval: float | None = None,
197
+ *,
198
+ on_start: Callable[[ResourceMetricCollector], None] | None = None,
199
+ on_stop: Callable[[ResourceMetricCollector], None] | None = None,
200
+ tag: str = 'metrics-daemon',
201
+ start: bool = True,
202
+ ) -> threading.Thread:
203
+ """Start a background daemon thread that collect and call the callback function periodically.
204
+
205
+ See also :func:`ResourceMetricCollector.daemonize`.
206
+
207
+ Args:
208
+ on_collect (Callable[[Dict[str, float]], bool]):
209
+ A callback function that will be called periodically. It takes a dictionary containing
210
+ the resource metrics and returns a boolean indicating whether to continue monitoring.
211
+ collector (Optional[ResourceMetricCollector]):
212
+ A :class:`ResourceMetricCollector` instance to collect metrics. If not given, it will
213
+ collect metrics for all GPUs and subprocess of the current process.
214
+ interval (Optional[float]):
215
+ The collect interval. If not given, use ``collector.interval``.
216
+ on_start (Optional[Callable[[ResourceMetricCollector], None]]):
217
+ A function to initialize the daemon thread and collector.
218
+ on_stop (Optional[Callable[[ResourceMetricCollector], None]]):
219
+ A function that do some necessary cleanup after the daemon thread is stopped.
220
+ tag (str):
221
+ The tag prefix used for metrics results.
222
+ start (bool):
223
+ Whether to start the daemon thread on return.
224
+
225
+ Returns: threading.Thread
226
+ A daemon thread object.
227
+
228
+ Examples:
229
+ .. code-block:: python
230
+
231
+ logger = ...
232
+
233
+ def on_collect(metrics): # will be called periodically
234
+ if logger.is_closed(): # closed manually by user
235
+ return False
236
+ logger.log(metrics)
237
+ return True
238
+
239
+ def on_stop(collector): # will be called only once at stop
240
+ if not logger.is_closed():
241
+ logger.close() # cleanup
242
+
243
+ # Record metrics to the logger in the background every 5 seconds.
244
+ # It will collect 5-second mean/min/max for each metric.
245
+ collect_in_background(
246
+ on_collect,
247
+ ResourceMetricCollector(Device.cuda.all()),
248
+ interval=5.0,
249
+ on_stop=on_stop,
250
+ )
251
+ """
252
+ if collector is None:
253
+ collector = ResourceMetricCollector()
254
+ if isinstance(interval, (int, float)) and interval > 0:
255
+ interval = float(interval)
256
+ elif interval is None:
257
+ interval = collector.interval
258
+ else:
259
+ raise ValueError(f'Invalid argument interval={interval!r}')
260
+
261
+ def target() -> None:
262
+ if on_start is not None:
263
+ on_start(collector)
264
+ try:
265
+ with collector(tag):
266
+ try:
267
+ next_snapshot = timer() + interval
268
+ while on_collect(collector.collect()):
269
+ time.sleep(max(0.0, next_snapshot - timer()))
270
+ next_snapshot += interval
271
+ except KeyboardInterrupt:
272
+ pass
273
+ finally:
274
+ if on_stop is not None:
275
+ on_stop(collector)
276
+
277
+ daemon = threading.Thread(target=target, name=tag, daemon=True)
278
+ daemon.collector = collector # type: ignore[attr-defined]
279
+ if start:
280
+ daemon.start()
281
+ return daemon
282
+
283
+
284
+ class ResourceMetricCollector: # pylint: disable=too-many-instance-attributes
285
+ """A class for collecting resource metrics.
286
+
287
+ Args:
288
+ devices (Iterable[Device]):
289
+ Set of Device instances for logging. If not given, all physical devices on board will be
290
+ used.
291
+ root_pids (Set[int]):
292
+ A set of PIDs, only the status of the descendant processes on the GPUs will be collected.
293
+ If not given, the PID of the current process will be used.
294
+ interval (float):
295
+ The snapshot interval for background daemon thread.
296
+
297
+ Core methods:
298
+
299
+ .. code-block:: python
300
+
301
+ collector.activate(tag='<tag>') # alias: start
302
+ collector.deactivate() # alias: stop
303
+ collector.clear(tag='<tag>')
304
+ collector.collect()
305
+
306
+ with collector(tag='<tag>'):
307
+ ...
308
+
309
+ collector.daemonize(on_collect_fn)
310
+
311
+ Examples:
312
+ >>> import os
313
+ >>> os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
314
+ >>> os.environ['CUDA_VISIBLE_DEVICES'] = '3,2,1,0'
315
+
316
+ >>> from nvitop import ResourceMetricCollector, Device
317
+
318
+ >>> collector = ResourceMetricCollector() # log all devices and descendant processes of the current process on the GPUs
319
+ >>> collector = ResourceMetricCollector(root_pids={1}) # log all devices and all GPU processes
320
+ >>> collector = ResourceMetricCollector(devices=Device.cuda.all()) # use the CUDA ordinal
321
+
322
+ >>> with collector(tag='<tag>'):
323
+ ... # Do something
324
+ ... collector.collect() # -> Dict[str, float]
325
+ # key -> '<tag>/<scope>/<metric (unit)>/<mean/min/max>'
326
+ {
327
+ '<tag>/host/cpu_percent (%)/mean': 8.967849777683456,
328
+ '<tag>/host/cpu_percent (%)/min': 6.1,
329
+ '<tag>/host/cpu_percent (%)/max': 28.1,
330
+ ...,
331
+ '<tag>/host/memory_percent (%)/mean': 21.5,
332
+ '<tag>/host/swap_percent (%)/mean': 0.3,
333
+ '<tag>/host/memory_used (GiB)/mean': 91.0136418208109,
334
+ '<tag>/host/load_average (%) (1 min)/mean': 10.251427386878328,
335
+ '<tag>/host/load_average (%) (5 min)/mean': 10.072539414569503,
336
+ '<tag>/host/load_average (%) (15 min)/mean': 11.91126970422139,
337
+ ...,
338
+ '<tag>/cuda:0 (gpu:3)/memory_used (MiB)/mean': 3.875,
339
+ '<tag>/cuda:0 (gpu:3)/memory_free (MiB)/mean': 11015.562499999998,
340
+ '<tag>/cuda:0 (gpu:3)/memory_total (MiB)/mean': 11019.437500000002,
341
+ '<tag>/cuda:0 (gpu:3)/memory_percent (%)/mean': 0.0,
342
+ '<tag>/cuda:0 (gpu:3)/gpu_utilization (%)/mean': 0.0,
343
+ '<tag>/cuda:0 (gpu:3)/memory_utilization (%)/mean': 0.0,
344
+ '<tag>/cuda:0 (gpu:3)/fan_speed (%)/mean': 22.0,
345
+ '<tag>/cuda:0 (gpu:3)/temperature (C)/mean': 25.0,
346
+ '<tag>/cuda:0 (gpu:3)/power_usage (W)/mean': 19.11166264116916,
347
+ ...,
348
+ '<tag>/cuda:1 (gpu:2)/memory_used (MiB)/mean': 8878.875,
349
+ ...,
350
+ '<tag>/cuda:2 (gpu:1)/memory_used (MiB)/mean': 8182.875,
351
+ ...,
352
+ '<tag>/cuda:3 (gpu:0)/memory_used (MiB)/mean': 9286.875,
353
+ ...,
354
+ '<tag>/pid:12345/host/cpu_percent (%)/mean': 151.34342772112265,
355
+ '<tag>/pid:12345/host/host_memory (MiB)/mean': 44749.72373447514,
356
+ '<tag>/pid:12345/host/host_memory_percent (%)/mean': 8.675082352111717,
357
+ '<tag>/pid:12345/host/running_time (min)': 336.23803206741576,
358
+ '<tag>/pid:12345/cuda:1 (gpu:4)/gpu_memory (MiB)/mean': 8861.0,
359
+ '<tag>/pid:12345/cuda:1 (gpu:4)/gpu_memory_percent (%)/mean': 80.4,
360
+ '<tag>/pid:12345/cuda:1 (gpu:4)/gpu_memory_utilization (%)/mean': 6.711118172407917,
361
+ '<tag>/pid:12345/cuda:1 (gpu:4)/gpu_sm_utilization (%)/mean': 48.23283397736476,
362
+ ...,
363
+ '<tag>/duration (s)': 7.247399162035435,
364
+ '<tag>/timestamp': 1655909466.9981883
365
+ }
366
+ """ # pylint: disable=line-too-long
367
+
368
+ DEVICE_METRICS: ClassVar[list[tuple[str, str, float | int]]] = [
369
+ # (<attribute>, <name>, <unit>)
370
+ # GPU memory metrics
371
+ ('memory_used', 'memory_used (MiB)', MiB),
372
+ ('memory_free', 'memory_free (MiB)', MiB),
373
+ ('memory_total', 'memory_total (MiB)', MiB),
374
+ ('memory_percent', 'memory_percent (%)', 1.0),
375
+ # GPU utilization metrics
376
+ ('gpu_utilization', 'gpu_utilization (%)', 1.0),
377
+ ('memory_utilization', 'memory_utilization (%)', 1.0),
378
+ # Miscellaneous
379
+ ('fan_speed', 'fan_speed (%)', 1.0),
380
+ ('temperature', 'temperature (C)', 1.0),
381
+ ('power_usage', 'power_usage (W)', 1000.0),
382
+ ]
383
+
384
+ PROCESS_METRICS: ClassVar[list[tuple[str, str | None, str, float | int]]] = [
385
+ # (<attribute>, <scope>, <name>, <unit>)
386
+ # Host resource metrics
387
+ ('cpu_percent', 'host', 'cpu_percent (%)', 1.0),
388
+ ('host_memory', 'host', 'host_memory (MiB)', MiB),
389
+ ('host_memory_percent', 'host', 'host_memory_percent (%)', 1.0),
390
+ ('running_time_in_seconds', 'host', 'running_time (min)', 60.0),
391
+ # GPU memory metrics
392
+ ('gpu_memory', None, 'gpu_memory (MiB)', MiB),
393
+ ('gpu_memory_percent', None, 'gpu_memory_percent (%)', 1.0),
394
+ ('gpu_memory_utilization', None, 'gpu_memory_utilization (%)', 1.0),
395
+ # GPU utilization metrics
396
+ ('gpu_sm_utilization', None, 'gpu_sm_utilization (%)', 1.0),
397
+ ]
398
+
399
+ def __init__(
400
+ self,
401
+ devices: Iterable[Device] | None = None,
402
+ *,
403
+ root_pids: Iterable[int] | None = None,
404
+ interval: float = 1.0,
405
+ ) -> None:
406
+ """Initialize the resource metric collector."""
407
+ if isinstance(interval, (int, float)) and interval > 0:
408
+ interval = float(interval)
409
+ else:
410
+ raise ValueError(f'Invalid argument interval={interval!r}')
411
+
412
+ if devices is None:
413
+ devices = Device.all()
414
+
415
+ root_pids: set[int] = {os.getpid()} if root_pids is None else set(root_pids)
416
+
417
+ self.interval: float = interval
418
+
419
+ self.devices: list[Device] = list(devices)
420
+ self.all_devices: list[Device] = []
421
+ self.leaf_devices: list[Device] = []
422
+ for device in self.devices:
423
+ self.all_devices.append(device)
424
+ mig_devices = device.mig_devices()
425
+ if len(mig_devices) > 0:
426
+ self.all_devices.extend(mig_devices)
427
+ self.leaf_devices.extend(mig_devices)
428
+ else:
429
+ self.leaf_devices.append(device)
430
+
431
+ self.root_pids: set[int] = root_pids
432
+ self._positive_processes: WeakSet[HostProcess] = WeakSet(
433
+ HostProcess(pid) for pid in self.root_pids
434
+ )
435
+ self._negative_processes: WeakSet[HostProcess] = WeakSet()
436
+
437
+ self._last_timestamp: float = timer() - 2.0 * self.interval
438
+ self._lock: threading.RLock = threading.RLock()
439
+ self._metric_buffer: _MetricBuffer | None = None
440
+ self._tags: set[str] = set()
441
+
442
+ self._daemon: threading.Thread = threading.Thread(
443
+ name='metrics-collector-daemon',
444
+ target=self._target,
445
+ daemon=True,
446
+ )
447
+ self._daemon_running: threading.Event = threading.Event()
448
+
449
+ def activate(self, tag: str) -> ResourceMetricCollector:
450
+ """Start a new metric collection with the given tag.
451
+
452
+ Args:
453
+ tag (str):
454
+ The name of the new metric collection. The tag will be used to identify the metric
455
+ collection. It must be a unique string.
456
+
457
+ Examples:
458
+ >>> collector = ResourceMetricCollector()
459
+
460
+ >>> collector.activate(tag='train') # key prefix -> 'train'
461
+ >>> collector.activate(tag='batch') # key prefix -> 'train/batch'
462
+ >>> collector.deactivate() # key prefix -> 'train'
463
+ >>> collector.deactivate() # the collector has been stopped
464
+ >>> collector.activate(tag='test') # key prefix -> 'test'
465
+ """
466
+ with self._lock:
467
+ if self._metric_buffer is None or tag not in self._tags:
468
+ self._tags.add(tag)
469
+ self._metric_buffer = _MetricBuffer(tag, self, prev=self._metric_buffer)
470
+ self._last_timestamp = timer() - 2.0 * self.interval
471
+ else:
472
+ raise RuntimeError(f'Resource metric collector is already started with tag "{tag}"')
473
+
474
+ self._daemon_running.set()
475
+ try:
476
+ self._daemon.start()
477
+ except RuntimeError:
478
+ pass
479
+
480
+ return self
481
+
482
+ start = activate
483
+
484
+ def deactivate(self, tag: str | None = None) -> ResourceMetricCollector:
485
+ """Stop the current collection with the given tag and remove all sub-tags.
486
+
487
+ If the tag is not specified, deactivate the current active collection. For nested
488
+ collections, the sub-collections will be deactivated as well.
489
+
490
+ Args:
491
+ tag (Optional[str]):
492
+ The tag to deactivate. If :data:`None`, the current active collection will be used.
493
+ """
494
+ with self._lock:
495
+ if self._metric_buffer is None:
496
+ if tag is not None:
497
+ raise RuntimeError('Resource metric collector has not been started yet.')
498
+ return self
499
+
500
+ if tag is None:
501
+ tag = self._metric_buffer.tag
502
+ elif tag not in self._tags:
503
+ raise RuntimeError(
504
+ f'Resource metric collector has not been started with tag "{tag}".',
505
+ )
506
+
507
+ buffer = self._metric_buffer
508
+ while True:
509
+ self._tags.remove(buffer.tag)
510
+ if buffer.tag == tag:
511
+ self._metric_buffer = buffer.prev
512
+ break
513
+ buffer = buffer.prev # type: ignore[assignment]
514
+
515
+ if self._metric_buffer is None:
516
+ self._daemon_running.clear()
517
+
518
+ return self
519
+
520
+ stop = deactivate
521
+
522
+ @contextlib.contextmanager
523
+ def context(self, tag: str) -> Generator[ResourceMetricCollector]:
524
+ """A context manager for starting and stopping resource metric collection.
525
+
526
+ Args:
527
+ tag (str):
528
+ The name of the new metric collection. The tag will be used to identify the metric
529
+ collection. It must be a unique string.
530
+
531
+ Examples:
532
+ >>> collector = ResourceMetricCollector()
533
+
534
+ >>> with collector.context(tag='train'): # key prefix -> 'train'
535
+ ... # Do something
536
+ ... collector.collect() # -> Dict[str, float]
537
+ """
538
+ try:
539
+ self.activate(tag=tag)
540
+ yield self
541
+ finally:
542
+ self.deactivate(tag=tag)
543
+
544
+ __call__ = context # alias for `with collector(tag='<tag>')`
545
+
546
+ def clear(self, tag: str | None = None) -> None:
547
+ """Clear the metric collection with the given tag.
548
+
549
+ If the tag is not specified, clear the current active collection. For nested collections,
550
+ the sub-collections will be cleared as well.
551
+
552
+ Args:
553
+ tag (Optional[str]):
554
+ The tag to clear. If :data:`None`, the current active collection will be reset.
555
+
556
+ Examples:
557
+ >>> collector = ResourceMetricCollector()
558
+
559
+ >>> with collector(tag='train'): # key prefix -> 'train'
560
+ ... time.sleep(5.0)
561
+ ... collector.collect() # metrics within the 5.0s interval
562
+ ...
563
+ ... time.sleep(5.0)
564
+ ... collector.collect() # metrics within the cumulative 10.0s interval
565
+ ...
566
+ ... collector.clear() # clear the active collection
567
+ ... time.sleep(5.0)
568
+ ... collector.collect() # metrics within the 5.0s interval
569
+ ...
570
+ ... with collector(tag='batch'): # key prefix -> 'train/batch'
571
+ ... collector.clear(tag='train') # clear both 'train' and 'train/batch'
572
+ """
573
+ with self._lock:
574
+ if self._metric_buffer is None:
575
+ if tag is not None:
576
+ raise RuntimeError('Resource metric collector has not been started yet.')
577
+ return
578
+
579
+ if tag is None:
580
+ tag = self._metric_buffer.tag
581
+ elif tag not in self._tags:
582
+ raise RuntimeError(
583
+ f'Resource metric collector has not been started with tag "{tag}".',
584
+ )
585
+
586
+ buffer = self._metric_buffer
587
+ while True:
588
+ buffer.clear()
589
+ if buffer.tag == tag:
590
+ break
591
+ buffer = buffer.prev # type: ignore[assignment]
592
+
593
+ reset = clear
594
+
595
+ def collect(self) -> dict[str, float]:
596
+ """Get the average resource consumption during collection."""
597
+ with self._lock:
598
+ if self._metric_buffer is None:
599
+ raise RuntimeError('Resource metric collector has not been started yet.')
600
+
601
+ if timer() - self._last_timestamp > self.interval / 2.0:
602
+ self.take_snapshots()
603
+ return self._metric_buffer.collect()
604
+
605
+ # pylint: disable-next=too-many-arguments
606
+ def daemonize(
607
+ self,
608
+ on_collect: Callable[[dict[str, float]], bool],
609
+ interval: float | None = None,
610
+ *,
611
+ on_start: Callable[[ResourceMetricCollector], None] | None = None,
612
+ on_stop: Callable[[ResourceMetricCollector], None] | None = None,
613
+ tag: str = 'metrics-daemon',
614
+ start: bool = True,
615
+ ) -> threading.Thread:
616
+ """Start a background daemon thread that collect and call the callback function periodically.
617
+
618
+ See also :func:`collect_in_background`.
619
+
620
+ Args:
621
+ on_collect (Callable[[Dict[str, float]], bool]):
622
+ A callback function that will be called periodically. It takes a dictionary containing
623
+ the resource metrics and returns a boolean indicating whether to continue monitoring.
624
+ interval (Optional[float]):
625
+ The collect interval. If not given, use ``collector.interval``.
626
+ on_start (Optional[Callable[[ResourceMetricCollector], None]]):
627
+ A function to initialize the daemon thread and collector.
628
+ on_stop (Optional[Callable[[ResourceMetricCollector], None]]):
629
+ A function that do some necessary cleanup after the daemon thread is stopped.
630
+ tag (str):
631
+ The tag prefix used for metrics results.
632
+ start (bool):
633
+ Whether to start the daemon thread on return.
634
+
635
+ Returns: threading.Thread
636
+ A daemon thread object.
637
+
638
+ Examples:
639
+ .. code-block:: python
640
+
641
+ logger = ...
642
+
643
+ def on_collect(metrics): # will be called periodically
644
+ if logger.is_closed(): # closed manually by user
645
+ return False
646
+ logger.log(metrics)
647
+ return True
648
+
649
+ def on_stop(collector): # will be called only once at stop
650
+ if not logger.is_closed():
651
+ logger.close() # cleanup
652
+
653
+ # Record metrics to the logger in the background every 5 seconds.
654
+ # It will collect 5-second mean/min/max for each metric.
655
+ ResourceMetricCollector(Device.cuda.all()).daemonize(
656
+ on_collect,
657
+ ResourceMetricCollector(Device.cuda.all()),
658
+ interval=5.0,
659
+ on_stop=on_stop,
660
+ )
661
+ """
662
+ return collect_in_background(
663
+ on_collect,
664
+ collector=self,
665
+ interval=interval,
666
+ on_start=on_start,
667
+ on_stop=on_stop,
668
+ tag=tag,
669
+ start=start,
670
+ )
671
+
672
+ def __del__(self) -> None:
673
+ """Clean up the demon thread on destruction."""
674
+ self._daemon_running.clear()
675
+
676
+ # pylint: disable-next=too-many-branches,too-many-locals,too-many-statements
677
+ def take_snapshots(self) -> SnapshotResult:
678
+ """Take snapshots of the current resource metrics and update the metric buffer."""
679
+ if len(self.root_pids) > 0:
680
+ all_gpu_processes: list[GpuProcess] = []
681
+ for device in self.leaf_devices:
682
+ all_gpu_processes.extend(device.processes().values())
683
+
684
+ gpu_processes = []
685
+ for process in all_gpu_processes:
686
+ if process.host in self._negative_processes:
687
+ continue
688
+
689
+ positive = True
690
+ if process.host not in self._positive_processes:
691
+ positive = False
692
+ p = process.host
693
+ parents = []
694
+ while p is not None:
695
+ parents.append(p)
696
+ if p in self._positive_processes:
697
+ positive = True
698
+ break
699
+ try:
700
+ p = p.parent() # type: ignore[assignment]
701
+ except host.PsutilError:
702
+ break
703
+ if positive:
704
+ self._positive_processes.update(parents)
705
+ else:
706
+ self._negative_processes.update(parents)
707
+
708
+ if positive:
709
+ gpu_processes.append(process)
710
+ else:
711
+ gpu_processes = []
712
+
713
+ timestamp = timer()
714
+ epoch_timestamp = time.time()
715
+ metrics = {}
716
+ device_snapshots = [device.as_snapshot() for device in self.all_devices]
717
+ gpu_process_snapshots = GpuProcess.take_snapshots(gpu_processes, failsafe=True)
718
+
719
+ metrics.update(
720
+ {
721
+ 'host/cpu_percent (%)': host.cpu_percent(),
722
+ 'host/memory_percent (%)': host.memory_percent(),
723
+ 'host/swap_percent (%)': host.swap_percent(),
724
+ 'host/memory_used (GiB)': host.virtual_memory().used / GiB,
725
+ },
726
+ )
727
+ load_average = host.load_average()
728
+ if load_average is not None:
729
+ metrics.update(
730
+ {
731
+ 'host/load_average (%) (1 min)': load_average[0],
732
+ 'host/load_average (%) (5 min)': load_average[1],
733
+ 'host/load_average (%) (15 min)': load_average[2],
734
+ },
735
+ )
736
+
737
+ device_identifiers = {}
738
+ for device_snapshot in device_snapshots:
739
+ identifier = f'gpu:{device_snapshot.index}'
740
+ if isinstance(device_snapshot.real, CudaDevice):
741
+ identifier = f'cuda:{device_snapshot.cuda_index} ({identifier})'
742
+ device_identifiers[device_snapshot.real] = identifier
743
+
744
+ for attr, name, unit in self.DEVICE_METRICS:
745
+ value = float(getattr(device_snapshot, attr)) / unit
746
+ metrics[f'{identifier}/{name}'] = value
747
+
748
+ for process_snapshot in gpu_process_snapshots:
749
+ device_identifier = device_identifiers[process_snapshot.device]
750
+ identifier = f'pid:{process_snapshot.pid}'
751
+
752
+ for attr, scope, name, unit in self.PROCESS_METRICS:
753
+ scope = scope or device_identifier
754
+ value = float(getattr(process_snapshot, attr)) / unit
755
+ metrics[f'{identifier}/{scope}/{name}'] = value
756
+
757
+ with self._lock:
758
+ if self._metric_buffer is not None:
759
+ self._metric_buffer.add(
760
+ metrics,
761
+ timestamp=timestamp,
762
+ epoch_timestamp=epoch_timestamp,
763
+ )
764
+ self._last_timestamp = timestamp
765
+
766
+ return SnapshotResult(device_snapshots, gpu_process_snapshots)
767
+
768
+ def _target(self) -> None:
769
+ self._daemon_running.wait()
770
+ while self._daemon_running.is_set():
771
+ next_snapshot = timer() + self.interval
772
+ self.take_snapshots()
773
+ time.sleep(max(0.0, next_snapshot - timer()))
774
+ next_snapshot += self.interval
775
+
776
+
777
+ class _MetricBuffer: # pylint: disable=missing-class-docstring,missing-function-docstring,too-many-instance-attributes
778
+ def __init__(
779
+ self,
780
+ tag: str,
781
+ collector: ResourceMetricCollector,
782
+ *,
783
+ prev: _MetricBuffer | None = None,
784
+ ) -> None:
785
+ self.collector: ResourceMetricCollector = collector
786
+ self.prev: _MetricBuffer | None = prev
787
+
788
+ self.tag: str = tag
789
+ self.key_prefix: str
790
+ if self.prev is not None:
791
+ self.key_prefix = f'{self.prev.key_prefix}/{self.tag}'
792
+ else:
793
+ self.key_prefix = self.tag
794
+
795
+ self.last_timestamp = self.start_timestamp = timer()
796
+ self.last_epoch_timestamp = time.time()
797
+ self.buffer: defaultdict[str, _StatisticsMaintainer] = defaultdict(
798
+ lambda: _StatisticsMaintainer(self.last_timestamp),
799
+ )
800
+
801
+ self.len = 0
802
+
803
+ def add(
804
+ self,
805
+ metrics: dict[str, float],
806
+ timestamp: float | None = None,
807
+ epoch_timestamp: float | None = None,
808
+ ) -> None:
809
+ if timestamp is None:
810
+ timestamp = timer()
811
+ if epoch_timestamp is None:
812
+ epoch_timestamp = time.time()
813
+
814
+ for key in set(self.buffer).difference(metrics):
815
+ self.buffer[key].add(math.nan, timestamp=timestamp)
816
+ for key, value in metrics.items():
817
+ self.buffer[key].add(value, timestamp=timestamp)
818
+ self.len += 1
819
+ self.last_timestamp = timestamp
820
+ self.last_epoch_timestamp = epoch_timestamp
821
+
822
+ if self.prev is not None:
823
+ self.prev.add(metrics, timestamp=timestamp)
824
+
825
+ def clear(self) -> None:
826
+ self.last_timestamp = self.start_timestamp = timer()
827
+ self.last_epoch_timestamp = time.time()
828
+ self.buffer.clear()
829
+ self.len = 0
830
+
831
+ def collect(self) -> dict[str, float]:
832
+ metrics = {
833
+ f'{self.key_prefix}/{key}/{name}': value
834
+ for key, stats in self.buffer.items()
835
+ for name, value in stats.items()
836
+ }
837
+ for key in tuple(metrics.keys()):
838
+ if key.endswith('host/running_time (min)/max'):
839
+ metrics[key[:-4]] = metrics[key]
840
+ del metrics[key]
841
+ elif key.endswith(('host/running_time (min)/mean', 'host/running_time (min)/min')):
842
+ del metrics[key]
843
+ metrics[f'{self.key_prefix}/duration (s)'] = timer() - self.start_timestamp
844
+ metrics[f'{self.key_prefix}/timestamp'] = time.time()
845
+ metrics[f'{self.key_prefix}/last_timestamp'] = self.last_epoch_timestamp
846
+ return metrics
847
+
848
+ def __len__(self) -> int:
849
+ return self.len
850
+
851
+
852
+ class _StatisticsMaintainer: # pylint: disable=missing-class-docstring,missing-function-docstring
853
+ def __init__(self, timestamp: float) -> None:
854
+ self.start_timestamp: float = timestamp
855
+ self.last_timestamp: float = math.nan
856
+ self.integral: float | None = None
857
+ self.last_value: float | None = None
858
+ self.min_value: float | None = None
859
+ self.max_value: float | None = None
860
+ self.has_nan: bool = False
861
+
862
+ def add(self, value: float, timestamp: float | None = None) -> None:
863
+ if timestamp is None:
864
+ timestamp = timer()
865
+
866
+ if math.isnan(value):
867
+ self.has_nan = True
868
+ return
869
+
870
+ if self.last_value is None:
871
+ self.integral = value * (timestamp - self.start_timestamp)
872
+ self.last_value = self.min_value = self.max_value = value
873
+ else:
874
+ # pylint: disable-next=line-too-long
875
+ self.integral += (value + self.last_value) * (timestamp - self.last_timestamp) / 2.0 # type: ignore[operator]
876
+ self.last_value = value
877
+ self.min_value = min(self.min_value, value) # type: ignore[type-var]
878
+ self.max_value = max(self.max_value, value) # type: ignore[type-var]
879
+
880
+ self.last_timestamp = timestamp
881
+
882
+ def mean(self) -> float:
883
+ if self.integral is None:
884
+ return math.nan
885
+
886
+ if self.has_nan:
887
+ return self.integral / (self.last_timestamp - self.start_timestamp)
888
+
889
+ timestamp = timer()
890
+ integral = self.integral + self.last_value * (timestamp - self.last_timestamp) # type: ignore[operator]
891
+ return integral / (timestamp - self.start_timestamp)
892
+
893
+ def min(self) -> float:
894
+ if self.min_value is None:
895
+ return math.nan
896
+ return self.min_value
897
+
898
+ def max(self) -> float:
899
+ if self.max_value is None:
900
+ return math.nan
901
+ return self.max_value
902
+
903
+ def last(self) -> float:
904
+ if self.last_value is None:
905
+ return math.nan
906
+ return self.last_value
907
+
908
+ def items(self) -> Iterable[tuple[str, float]]:
909
+ yield ('mean', self.mean())
910
+ yield ('min', self.min())
911
+ yield ('max', self.max())
912
+ yield ('last', self.last())
.venv/lib/python3.10/site-packages/nvitop/api/device.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/lib/python3.10/site-packages/nvitop/api/host.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is part of nvitop, the interactive NVIDIA-GPU process viewer.
2
+ #
3
+ # Copyright 2021-2025 Xuehai Pan. All Rights Reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ # ==============================================================================
17
+ """Shortcuts for package ``psutil``.
18
+
19
+ ``psutil`` is a cross-platform library for retrieving information on running processes and system
20
+ utilization (CPU, memory, disks, network, sensors) in Python.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import os as _os
26
+
27
+ import psutil as _psutil
28
+ from psutil import * # noqa: F403 # pylint: disable=wildcard-import,unused-wildcard-import,redefined-builtin
29
+ from psutil import ( # noqa: F401
30
+ LINUX,
31
+ MACOS,
32
+ POSIX,
33
+ WINDOWS,
34
+ AccessDenied,
35
+ Error,
36
+ NoSuchProcess,
37
+ Process,
38
+ ZombieProcess,
39
+ boot_time,
40
+ cpu_percent,
41
+ pids,
42
+ swap_memory,
43
+ virtual_memory,
44
+ )
45
+ from psutil import Error as PsutilError # pylint: disable=reimported
46
+
47
+
48
+ __all__ = [
49
+ 'WINDOWS_SUBSYSTEM_FOR_LINUX',
50
+ 'WSL',
51
+ 'PsutilError',
52
+ 'getuser',
53
+ 'hostname',
54
+ 'load_average',
55
+ 'memory_percent',
56
+ 'ppid_map',
57
+ 'reverse_ppid_map',
58
+ 'swap_percent',
59
+ 'uptime',
60
+ ]
61
+ __all__ += [name for name in _psutil.__all__ if not name.startswith('_') and name != 'Error']
62
+
63
+
64
+ del Error # renamed to PsutilError
65
+
66
+
67
+ def getuser() -> str:
68
+ """Get the current username from the environment or password database."""
69
+ import getpass # pylint: disable=import-outside-toplevel
70
+
71
+ try:
72
+ return getpass.getuser()
73
+ except (ModuleNotFoundError, OSError):
74
+ return _os.getlogin()
75
+
76
+
77
+ def hostname() -> str:
78
+ """Get the hostname of the machine."""
79
+ import platform # pylint: disable=import-outside-toplevel
80
+
81
+ return platform.node()
82
+
83
+
84
+ if hasattr(_psutil, 'getloadavg'):
85
+
86
+ def load_average() -> tuple[float, float, float]:
87
+ """Get the system load average."""
88
+ return _psutil.getloadavg()
89
+
90
+ else:
91
+
92
+ def load_average() -> None: # type: ignore[misc]
93
+ """Get the system load average."""
94
+ return
95
+
96
+
97
+ def uptime() -> float:
98
+ """Get the system uptime."""
99
+ import time as _time # pylint: disable=import-outside-toplevel
100
+
101
+ return _time.time() - boot_time()
102
+
103
+
104
+ def memory_percent() -> float:
105
+ """The percentage usage of virtual memory, calculated as ``(total - available) / total * 100``."""
106
+ return virtual_memory().percent
107
+
108
+
109
+ def swap_percent() -> float:
110
+ """The percentage usage of virtual memory, calculated as ``used / total * 100``."""
111
+ return swap_memory().percent
112
+
113
+
114
+ def ppid_map() -> dict[int, int]:
115
+ """Obtain a ``{pid: ppid, ...}`` dict for all running processes in one shot."""
116
+ ret = {}
117
+ for pid in pids():
118
+ try:
119
+ ret[pid] = Process(pid).ppid()
120
+ except (NoSuchProcess, ZombieProcess): # noqa: PERF203
121
+ pass
122
+ return ret
123
+
124
+
125
+ try:
126
+ from psutil import _ppid_map as ppid_map # type: ignore[no-redef] # noqa: F811,RUF100
127
+ except ImportError:
128
+ pass
129
+
130
+
131
+ def reverse_ppid_map() -> dict[int, list[int]]:
132
+ """Obtain a ``{ppid: [pid, ...], ...}`` dict for all running processes in one shot."""
133
+ from collections import defaultdict # pylint: disable=import-outside-toplevel
134
+
135
+ ret = defaultdict(list)
136
+ for pid, ppid in ppid_map().items():
137
+ ret[ppid].append(pid)
138
+
139
+ return ret
140
+
141
+
142
+ if LINUX:
143
+ WSL = _os.getenv('WSL_DISTRO_NAME', default=None)
144
+ if WSL is not None and WSL == '':
145
+ WSL = 'WSL'
146
+ else:
147
+ WSL = None
148
+ WINDOWS_SUBSYSTEM_FOR_LINUX = WSL
149
+ """The Linux distribution name of the Windows Subsystem for Linux."""
.venv/lib/python3.10/site-packages/nvitop/api/libcuda.py ADDED
@@ -0,0 +1,747 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is part of nvitop, the interactive NVIDIA-GPU process viewer.
2
+ #
3
+ # Copyright 2021-2025 Xuehai Pan. All Rights Reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ # ==============================================================================
17
+ """Python bindings for the `CUDA Driver APIs <https://docs.nvidia.com/cuda/cuda-driver-api>`_."""
18
+
19
+ # pylint: disable=invalid-name
20
+
21
+ from __future__ import annotations
22
+
23
+ import ctypes as _ctypes
24
+ import itertools as _itertools
25
+ import platform as _platform
26
+ import string as _string
27
+ import sys as _sys
28
+ import threading as _threading
29
+ from typing import TYPE_CHECKING as _TYPE_CHECKING
30
+ from typing import Any as _Any
31
+ from typing import ClassVar as _ClassVar
32
+
33
+
34
+ if _TYPE_CHECKING:
35
+ from collections.abc import Callable as _Callable
36
+ from typing_extensions import Self as _Self # Python 3.11+
37
+ from typing_extensions import TypeAlias as _TypeAlias # Python 3.10+
38
+
39
+
40
+ # pylint: disable-next=missing-class-docstring,too-few-public-methods
41
+ class _struct_c_CUdevice_t(_ctypes.Structure):
42
+ pass # opaque handle
43
+
44
+
45
+ _c_CUdevice_t: _TypeAlias = _ctypes.POINTER( # type: ignore[valid-type] # noqa: PYI042
46
+ _struct_c_CUdevice_t,
47
+ )
48
+
49
+ _CUresult_t: _TypeAlias = _ctypes.c_uint
50
+
51
+ # Error codes #
52
+ # pylint: disable=line-too-long
53
+ CUDA_SUCCESS = 0
54
+ """The API call returned with no errors. In the case of query calls, this also means that the operation being queried is complete (see :func:`cuEventQuery` and :func:`cuStreamQuery`)."""
55
+ CUDA_ERROR_INVALID_VALUE = 1
56
+ """This indicates that one or more of the parameters passed to the API call is not within an acceptable range of values."""
57
+ CUDA_ERROR_OUT_OF_MEMORY = 2
58
+ """The API call failed because it was unable to allocate enough memory to perform the requested operation."""
59
+ CUDA_ERROR_NOT_INITIALIZED = 3
60
+ """This indicates that the CUDA driver has not been initialized with :func:`cuInit` or that initialization has failed."""
61
+ CUDA_ERROR_DEINITIALIZED = 4
62
+ """This indicates that the CUDA driver is in the process of shutting down."""
63
+ CUDA_ERROR_PROFILER_DISABLED = 5
64
+ """This indicates profiler is not initialized for this run. This can happen when the application is running with external profiling tools like visual profiler."""
65
+ CUDA_ERROR_STUB_LIBRARY = 34
66
+ """This indicates that the CUDA driver that the application has loaded is a stub library. Applications that run with the stub rather than a real driver loaded will result in CUDA API returning this error."""
67
+ CUDA_ERROR_DEVICE_UNAVAILABLE = 46
68
+ """This indicates that requested CUDA device is unavailable at the current time. Devices are often unavailable due to use of :data:`CU_COMPUTEMODE_EXCLUSIVE_PROCESS` or :data:`CU_COMPUTEMODE_PROHIBITED`."""
69
+ CUDA_ERROR_NO_DEVICE = 100
70
+ """This indicates that no CUDA - capable devices were detected by the installed CUDA driver."""
71
+ CUDA_ERROR_INVALID_DEVICE = 101
72
+ """This indicates that the device ordinal supplied by the user does not correspond to a valid CUDA device or that the action requested is invalid for the specified device."""
73
+ CUDA_ERROR_DEVICE_NOT_LICENSED = 102
74
+ """This error indicates that the Grid license is not applied."""
75
+ CUDA_ERROR_INVALID_IMAGE = 200
76
+ """This indicates that the device kernel image is invalid. This can also indicate an invalid CUDA module."""
77
+ CUDA_ERROR_INVALID_CONTEXT = 201
78
+ """This most frequently indicates that there is no context bound to the current thread. This can also be returned if the context passed to an API call is not a valid handle (such as a context that has had :func:`cuCtxDestroy` invoked on it). This can also be returned if a user mixes different API versions (i.e. 3010 context with 3020 API calls). See :func:`cuCtxGetApiVersion` for more details."""
79
+ CUDA_ERROR_MAP_FAILED = 205
80
+ """This indicates that a map or register operation has failed."""
81
+ CUDA_ERROR_UNMAP_FAILED = 206
82
+ """This indicates that an unmap or unregister operation has failed."""
83
+ CUDA_ERROR_ARRAY_IS_MAPPED = 207
84
+ """This indicates that the specified array is currently mapped and thus cannot be destroyed."""
85
+ CUDA_ERROR_ALREADY_MAPPED = 208
86
+ """This indicates that the resource is already mapped."""
87
+ CUDA_ERROR_NO_BINARY_FOR_GPU = 209
88
+ """This indicates that there is no kernel image available that is suitable for the device. This can occur when a user specifies code generation options for a particular CUDA source file that do not include the corresponding device configuration."""
89
+ CUDA_ERROR_ALREADY_ACQUIRED = 210
90
+ """This indicates that a resource has already been acquired."""
91
+ CUDA_ERROR_NOT_MAPPED = 211
92
+ """This indicates that a resource is not mapped."""
93
+ CUDA_ERROR_NOT_MAPPED_AS_ARRAY = 212
94
+ """This indicates that a mapped resource is not available for access as an array."""
95
+ CUDA_ERROR_NOT_MAPPED_AS_POINTER = 213
96
+ """This indicates that a mapped resource is not available for access as a pointer."""
97
+ CUDA_ERROR_ECC_UNCORRECTABLE = 214
98
+ """This indicates that an uncorrectable ECC error was detected during execution."""
99
+ CUDA_ERROR_UNSUPPORTED_LIMIT = 215
100
+ """This indicates that the :class:`CUlimit` passed to the API call is not supported by the active device."""
101
+ CUDA_ERROR_CONTEXT_ALREADY_IN_USE = 216
102
+ """This indicates that the :class:`CUcontext` passed to the API call can only be bound to a single CPU thread at a time but is already bound to a CPU thread."""
103
+ CUDA_ERROR_PEER_ACCESS_UNSUPPORTED = 217
104
+ """This indicates that peer access is not supported across the given devices."""
105
+ CUDA_ERROR_INVALID_PTX = 218
106
+ """This indicates that a PTX JIT compilation failed."""
107
+ CUDA_ERROR_INVALID_GRAPHICS_CONTEXT = 219
108
+ """This indicates an error with OpenGL or DirectX context."""
109
+ CUDA_ERROR_NVLINK_UNCORRECTABLE = 220
110
+ """This indicates that an uncorrectable NVLink error was detected during the execution."""
111
+ CUDA_ERROR_JIT_COMPILER_NOT_FOUND = 221
112
+ """This indicates that the PTX JIT compiler library was not found."""
113
+ CUDA_ERROR_UNSUPPORTED_PTX_VERSION = 222
114
+ """This indicates that the provided PTX was compiled with an unsupported toolchain."""
115
+ CUDA_ERROR_JIT_COMPILATION_DISABLED = 223
116
+ """This indicates that the PTX JIT compilation was disabled."""
117
+ CUDA_ERROR_UNSUPPORTED_EXEC_AFFINITY = 224
118
+ """This indicates that the :class:`CUexecAffinityType` passed to the API call is not supported by the active device."""
119
+ CUDA_ERROR_INVALID_SOURCE = 300
120
+ """This indicates that the device kernel source is invalid. This includes compilation / linker errors encountered in device code or user error."""
121
+ CUDA_ERROR_FILE_NOT_FOUND = 301
122
+ """This indicates that the file specified was not found."""
123
+ CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND = 302
124
+ """This indicates that a link to a shared object failed to resolve."""
125
+ CUDA_ERROR_SHARED_OBJECT_INIT_FAILED = 303
126
+ """This indicates that initialization of a shared object failed."""
127
+ CUDA_ERROR_OPERATING_SYSTEM = 304
128
+ """This indicates that an OS call failed."""
129
+ CUDA_ERROR_INVALID_HANDLE = 400
130
+ """This indicates that a resource handle passed to the API call was not valid. Resource handles are opaque types like :class:`CUstream` and :class:`CUevent`."""
131
+ CUDA_ERROR_ILLEGAL_STATE = 401
132
+ """This indicates that a resource required by the API call is not in a valid state to perform the requested operation."""
133
+ CUDA_ERROR_NOT_FOUND = 500
134
+ """This indicates that a named symbol was not found. Examples of symbols are global / constant variable names, driver function names, texture names, and surface names."""
135
+ CUDA_ERROR_NOT_READY = 600
136
+ """This indicates that asynchronous operations issued previously have not completed yet. This result is not actually an error, but must be indicated differently than :data:`CUDA_SUCCESS` (which indicates completion). Calls that may return this value include :func:`cuEventQuery` and :func:`cuStreamQuery`."""
137
+ CUDA_ERROR_ILLEGAL_ADDRESS = 700
138
+ """While executing a kernel, the device encountered a load or store instruction on an invalid memory address. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched."""
139
+ CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES = 701
140
+ """This indicates that a launch did not occur because it did not have appropriate resources. This error usually indicates that the user has attempted to pass too many arguments to the device kernel, or the kernel launch specifies too many threads for the kernel's register count. Passing arguments of the wrong size (i.e. a 64 - bit pointer when a 32 - bit int is expected) is equivalent to passing too many arguments and can also result in this error."""
141
+ CUDA_ERROR_LAUNCH_TIMEOUT = 702
142
+ """This indicates that the device kernel took too long to execute. This can only occur if timeouts are enabled - see the device attribute :data:`CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT` for more information. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched."""
143
+ CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING = 703
144
+ """This error indicates a kernel launch that uses an incompatible texturing mode."""
145
+ CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED = 704
146
+ """This error indicates that a call to :func:`cuCtxEnablePeerAccess` is trying to re - enable peer access to a context which has already had peer access to it enabled."""
147
+ CUDA_ERROR_PEER_ACCESS_NOT_ENABLED = 705
148
+ """This error indicates that :func:`cuCtxDisablePeerAccess` is trying to disable peer access which has not been enabled yet via :func:`cuCtxEnablePeerAccess`."""
149
+ CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE = 708
150
+ """This error indicates that the primary context for the specified device has already been initialized."""
151
+ CUDA_ERROR_CONTEXT_IS_DESTROYED = 709
152
+ """This error indicates that the context current to the calling thread has been destroyed using :func:`cuCtxDestroy`, or is a primary context which has not yet been initialized."""
153
+ CUDA_ERROR_ASSERT = 710
154
+ """A device - side assert triggered during kernel execution. The context cannot be used anymore, and must be destroyed. All existing device memory allocations from this context are invalid and must be reconstructed if the program is to continue using CUDA."""
155
+ CUDA_ERROR_TOO_MANY_PEERS = 711
156
+ """This error indicates that the hardware resources required to enable peer access have been exhausted for one or more of the devices passed to :func:`cuCtxEnablePeerAccess`."""
157
+ CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED = 712
158
+ """This error indicates that the memory range passed to :func:`cuMemHostRegister` has already been registered."""
159
+ CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED = 713
160
+ """This error indicates that the pointer passed to :func:`cuMemHostUnregister` does not correspond to any currently registered memory region."""
161
+ CUDA_ERROR_HARDWARE_STACK_ERROR = 714
162
+ """While executing a kernel, the device encountered a stack error. This can be due to stack corruption or exceeding the stack size limit. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched."""
163
+ CUDA_ERROR_ILLEGAL_INSTRUCTION = 715
164
+ """While executing a kernel, the device encountered an illegal instruction. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched."""
165
+ CUDA_ERROR_MISALIGNED_ADDRESS = 716
166
+ """While executing a kernel, the device encountered a load or store instruction on a memory address which is not aligned. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched."""
167
+ CUDA_ERROR_INVALID_ADDRESS_SPACE = 717
168
+ """While executing a kernel, the device encountered an instruction which can only operate on memory locations in certain address spaces (global, shared, or local), but was supplied a memory address not belonging to an allowed address space. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched."""
169
+ CUDA_ERROR_INVALID_PC = 718
170
+ """While executing a kernel, the device program counter wrapped its address space. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched."""
171
+ CUDA_ERROR_LAUNCH_FAILED = 719
172
+ """An exception occurred on the device while executing a kernel. Common causes include dereferencing an invalid device pointer and accessing out of bounds shared memory. Less common cases can be system specific - more information about these cases can be found in the system specific user guide. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched."""
173
+ CUDA_ERROR_COOPERATIVE_LAUNCH_TOO_LARGE = 720
174
+ """This error indicates that the number of blocks launched per grid for a kernel that was launched via either :func:`cuLaunchCooperativeKernel` or :func:`cuLaunchCooperativeKernelMultiDevice` exceeds the maximum number of blocks as allowed by :func:`cuOccupancyMaxActiveBlocksPerMultiprocessor` or :func:`cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags` times the number of multiprocessors as specified by the device attribute :data:`CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT`."""
175
+ CUDA_ERROR_NOT_PERMITTED = 800
176
+ """This error indicates that the attempted operation is not permitted."""
177
+ CUDA_ERROR_NOT_SUPPORTED = 801
178
+ """This error indicates that the attempted operation is not supported on the current system or device."""
179
+ CUDA_ERROR_SYSTEM_NOT_READY = 802
180
+ """This error indicates that the system is not yet ready to start any CUDA work. To continue using CUDA, verify the system configuration is in a valid state and all required driver daemons are actively running. More information about this error can be found in the system specific user guide."""
181
+ CUDA_ERROR_SYSTEM_DRIVER_MISMATCH = 803
182
+ """This error indicates that there is a mismatch between the versions of the display driver and the CUDA driver. Refer to the compatibility documentation for supported versions."""
183
+ CUDA_ERROR_COMPAT_NOT_SUPPORTED_ON_DEVICE = 804
184
+ """This error indicates that the system was upgraded to run with forward compatibility but the visible hardware detected by CUDA does not support this configuration. Refer to the compatibility documentation for the supported hardware matrix or ensure that only supported hardware is visible during initialization via the ``CUDA_VISIBLE_DEVICES`` environment variable."""
185
+ CUDA_ERROR_MPS_CONNECTION_FAILED = 805
186
+ """This error indicates that the MPS client failed to connect to the MPS control daemon or the MPS server."""
187
+ CUDA_ERROR_MPS_RPC_FAILURE = 806
188
+ """This error indicates that the remote procedural call between the MPS server and the MPS client failed."""
189
+ CUDA_ERROR_MPS_SERVER_NOT_READY = 807
190
+ """This error indicates that the MPS server is not ready to accept new MPS client requests. This error can be returned when the MPS server is in the process of recovering from a fatal failure."""
191
+ CUDA_ERROR_MPS_MAX_CLIENTS_REACHED = 808
192
+ """This error indicates that the hardware resources required to create MPS client have been exhausted."""
193
+ CUDA_ERROR_MPS_MAX_CONNECTIONS_REACHED = 809
194
+ """This error indicates the the hardware resources required to support device connections have been exhausted."""
195
+ CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED = 900
196
+ """This error indicates that the operation is not permitted when the stream is capturing."""
197
+ CUDA_ERROR_STREAM_CAPTURE_INVALIDATED = 901
198
+ """This error indicates that the current capture sequence on the stream has been invalidated due to a previous error."""
199
+ CUDA_ERROR_STREAM_CAPTURE_MERGE = 902
200
+ """This error indicates that the operation would have resulted in a merge of two independent capture sequences."""
201
+ CUDA_ERROR_STREAM_CAPTURE_UNMATCHED = 903
202
+ """This error indicates that the capture was initiated not in this stream."""
203
+ CUDA_ERROR_STREAM_CAPTURE_UNJOINED = 904
204
+ """This error indicates that the capture sequence contains a fork that was not joined to the primary stream."""
205
+ CUDA_ERROR_STREAM_CAPTURE_ISOLATION = 905
206
+ """This error indicates that a dependency would have been created which crosses the capture sequence boundary. Only implicit in -stream ordering dependencies are allowed to cross the boundary."""
207
+ CUDA_ERROR_STREAM_CAPTURE_IMPLICIT = 906
208
+ """This error indicates a disallowed implicit dependency on a current capture sequence from :func:`cudaStreamLegacy`."""
209
+ CUDA_ERROR_CAPTURED_EVENT = 907
210
+ """This error indicates that the operation is not permitted on an event which was last recorded in a capturing stream."""
211
+ CUDA_ERROR_STREAM_CAPTURE_WRONG_THREAD = 908
212
+ """A stream capture sequence not initiated with the :data:`CU_STREAM_CAPTURE_MODE_RELAXED` argument to :func:`cuStreamBeginCapture` was passed to :func:`cuStreamEndCapture` in a different thread."""
213
+ CUDA_ERROR_TIMEOUT = 909
214
+ """This error indicates that the timeout specified for the wait operation has lapsed."""
215
+ CUDA_ERROR_GRAPH_EXEC_UPDATE_FAILURE = 910
216
+ """This error indicates that the graph update was not performed because it included changes which violated constraints specific to instantiated graph update."""
217
+ CUDA_ERROR_EXTERNAL_DEVICE = 911
218
+ """This indicates that an async error has occurred in a device outside of CUDA. If CUDA was waiting for an external device's signal before consuming shared data, the external device signaled an error indicating that the data is not valid for consumption. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched."""
219
+ CUDA_ERROR_UNKNOWN = 999
220
+ """This indicates that an unknown internal error has occurred."""
221
+ # pylint: enable=line-too-long
222
+
223
+
224
+ # Error Checking #
225
+ class CUDAError(Exception):
226
+ """Base exception class for CUDA driver query errors."""
227
+
228
+ _value_class_mapping: _ClassVar[dict[int, type[CUDAError]]] = {}
229
+ _errcode_to_string: _ClassVar[dict[int, str]] = { # List of currently known error codes
230
+ CUDA_ERROR_NOT_INITIALIZED: 'Initialization error.',
231
+ CUDA_ERROR_NOT_FOUND: 'Named symbol not found.',
232
+ CUDA_ERROR_INVALID_VALUE: 'Invalid argument.',
233
+ CUDA_ERROR_NO_DEVICE: 'No CUDA-capable device is detected.',
234
+ CUDA_ERROR_INVALID_DEVICE: 'Invalid device ordinal.',
235
+ CUDA_ERROR_SYSTEM_DRIVER_MISMATCH: 'System has unsupported display driver / CUDA driver combination.',
236
+ CUDA_ERROR_DEINITIALIZED: 'Driver shutting down.',
237
+ CUDA_ERROR_COMPAT_NOT_SUPPORTED_ON_DEVICE: 'Forward compatibility was attempted on non supported Hardware.',
238
+ CUDA_ERROR_INVALID_CONTEXT: 'Invalid device context.',
239
+ } # fmt:skip
240
+ _errcode_to_name: _ClassVar[dict[int, str]] = {}
241
+ value: int
242
+
243
+ def __new__(cls, value: int) -> _Self:
244
+ """Map value to a proper subclass of :class:`CUDAError`."""
245
+ if cls is CUDAError:
246
+ # pylint: disable-next=self-cls-assignment
247
+ cls = CUDAError._value_class_mapping.get(value, cls) # type: ignore[assignment]
248
+ obj = Exception.__new__(cls)
249
+ obj.value = value
250
+ return obj
251
+
252
+ def __repr__(self) -> str:
253
+ """Return a string representation of the error."""
254
+ # pylint: disable=no-member
255
+ try:
256
+ if self.value not in CUDAError._errcode_to_string:
257
+ CUDAError._errcode_to_string[self.value] = '{}.'.format(
258
+ cuGetErrorString(self.value).rstrip('.').capitalize(),
259
+ )
260
+ if self.value not in CUDAError._errcode_to_name:
261
+ CUDAError._errcode_to_name[self.value] = cuGetErrorName(self.value)
262
+ return (
263
+ f'{CUDAError._errcode_to_string[self.value]} '
264
+ f'Code: {CUDAError._errcode_to_name[self.value]} ({self.value}).'
265
+ )
266
+ except CUDAError:
267
+ return f'CUDA Error with code {self.value}.'
268
+
269
+ def __eq__(self, other: object) -> bool:
270
+ """Test equality to other object."""
271
+ if not isinstance(other, CUDAError):
272
+ return NotImplemented
273
+ return self.value == other.value # pylint: disable=no-member
274
+
275
+ def __reduce__(self) -> tuple[type[CUDAError], tuple[int]]:
276
+ """Return state information for pickling."""
277
+ return CUDAError, (self.value,) # pylint: disable=no-member
278
+
279
+
280
+ def cudaExceptionClass(cudaErrorCode: int, /) -> type[CUDAError]:
281
+ """Map value to a proper subclass of :class:`CUDAError`.
282
+
283
+ Raises:
284
+ ValueError: If the error code is not valid.
285
+ """
286
+ if cudaErrorCode not in CUDAError._value_class_mapping: # pylint: disable=protected-access
287
+ raise ValueError(f'cudaErrorCode {cudaErrorCode} is not valid.')
288
+ return CUDAError._value_class_mapping[cudaErrorCode] # pylint: disable=protected-access
289
+
290
+
291
+ def _extract_cuda_errors_as_classes() -> None:
292
+ """Generate a hierarchy of classes on top of :class:`CUDAError` class.
293
+
294
+ Each CUDA Error gets a new :class:`CUDAError` subclass. This way try-except blocks can filter
295
+ appropriate exceptions more easily.
296
+
297
+ :class:`CUDAError` is a parent class. Each ``CUDA_ERROR_*`` gets it's own subclass.
298
+ e.g. :data:`CUDA_ERROR_INVALID_VALUE` will be turned into :class:`CUDAError_InvalidValue`.
299
+ """
300
+ this_module = _sys.modules[__name__]
301
+ cuda_error_names = [x for x in dir(this_module) if x.startswith('CUDA_ERROR_')]
302
+ for err_name in cuda_error_names:
303
+ # e.g. Turn CUDA_ERROR_INVALID_VALUE into CUDAError_InvalidValue
304
+ pascal_case = _string.capwords(err_name.replace('CUDA_ERROR_', ''), '_').replace('_', '')
305
+ class_name = f'CUDAError_{pascal_case}'
306
+ err_val = getattr(this_module, err_name)
307
+
308
+ def gen_new(value: int) -> _Callable[[type[CUDAError]], CUDAError]:
309
+ def new(cls: type[CUDAError]) -> CUDAError:
310
+ return CUDAError.__new__(cls, value)
311
+
312
+ return new
313
+
314
+ # pylint: disable=protected-access
315
+ new_error_class = type(class_name, (CUDAError,), {'__new__': gen_new(err_val)})
316
+ new_error_class.__module__ = __name__
317
+ if err_val in CUDAError._errcode_to_string:
318
+ new_error_class.__doc__ = (
319
+ f'CUDA Error: {CUDAError._errcode_to_string[err_val]} '
320
+ f'Code: :data:`{err_name}` ({err_val}).'
321
+ )
322
+ else:
323
+ new_error_class.__doc__ = f'CUDA Error with code :data:`{err_name}` ({err_val})'
324
+ setattr(this_module, class_name, new_error_class)
325
+ CUDAError._value_class_mapping[err_val] = new_error_class
326
+ CUDAError._errcode_to_name[err_val] = err_name
327
+
328
+
329
+ # Add explicit references to appease linters
330
+ class __CUDAError(CUDAError):
331
+ value: int
332
+
333
+ def __new__(cls) -> CUDAError: # type: ignore[misc,empty-body]
334
+ ...
335
+
336
+
337
+ CUDAError_NotInitialized: type[__CUDAError]
338
+ CUDAError_NotFound: type[__CUDAError]
339
+ CUDAError_InvalidValue: type[__CUDAError]
340
+ CUDAError_NoDevice: type[__CUDAError]
341
+ CUDAError_InvalidDevice: type[__CUDAError]
342
+ CUDAError_SystemDriverMismatch: type[__CUDAError]
343
+ CUDAError_Deinitialized: type[__CUDAError]
344
+ CUDAError_CompatNotSupportedOnDevice: type[__CUDAError]
345
+ CUDAError_InvalidContext: type[__CUDAError]
346
+
347
+ _extract_cuda_errors_as_classes()
348
+ del _extract_cuda_errors_as_classes
349
+
350
+
351
+ def _cudaCheckReturn(ret: _Any, /) -> _Any:
352
+ if ret != CUDA_SUCCESS:
353
+ raise CUDAError(ret)
354
+ return ret
355
+
356
+
357
+ # Function access #
358
+ __cudaLib: _ctypes.CDLL | None = None
359
+ __initialized: bool = False
360
+ __libLoadLock: _threading.Lock = _threading.Lock()
361
+ # Function pointers are cached to prevent unnecessary libLoadLock locking
362
+ __cudaGetFunctionPointer_cache: dict[str, _ctypes._CFuncPtr] = {} # type: ignore[name-defined]
363
+
364
+
365
+ def __cudaGetFunctionPointer(name: str) -> _ctypes._CFuncPtr: # type: ignore[name-defined]
366
+ """Get the function pointer from the CUDA driver library.
367
+
368
+ Raises:
369
+ CUDAError_NotInitialized:
370
+ If cannot found the CUDA driver library.
371
+ CUDAError_NotFound:
372
+ If cannot found the function pointer.
373
+ """
374
+ if name in __cudaGetFunctionPointer_cache:
375
+ return __cudaGetFunctionPointer_cache[name]
376
+
377
+ with __libLoadLock:
378
+ # Ensure library was loaded
379
+ if __cudaLib is None:
380
+ raise CUDAError(CUDA_ERROR_NOT_INITIALIZED)
381
+ try:
382
+ __cudaGetFunctionPointer_cache[name] = getattr(__cudaLib, name)
383
+ return __cudaGetFunctionPointer_cache[name]
384
+ except AttributeError as ex:
385
+ raise CUDAError(CUDA_ERROR_NOT_FOUND) from ex
386
+
387
+
388
+ def __LoadCudaLibrary() -> None:
389
+ """Load the library if it isn't loaded already.
390
+
391
+ Raises:
392
+ CUDAError_NotInitialized:
393
+ If cannot found the CUDA driver library.
394
+ """
395
+ global __cudaLib # pylint: disable=global-statement
396
+
397
+ if __cudaLib is None:
398
+ # Lock to ensure only one caller loads the library
399
+ with __libLoadLock:
400
+ # Ensure the library still isn't loaded
401
+ if __cudaLib is None:
402
+ # Platform specific libcuda location
403
+ system = _platform.system()
404
+ if system == 'Darwin':
405
+ lib_filenames = [
406
+ 'libcuda.1.dylib', # check library path first
407
+ 'libcuda.dylib',
408
+ '/usr/local/cuda/lib/libcuda.1.dylib',
409
+ '/usr/local/cuda/lib/libcuda.dylib',
410
+ ]
411
+ elif system == 'Linux':
412
+ lib_filenames = [
413
+ 'libcuda.so', # check library path first
414
+ '/usr/lib64/nvidia/libcuda.so', # Redhat/CentOS/Fedora
415
+ '/usr/lib/x86_64-linux-gnu/libcuda.so', # Ubuntu
416
+ '/usr/lib/wsl/lib/libcuda.so', # WSL
417
+ ]
418
+ # Also add libraries with version suffix `.1`
419
+ lib_filenames = list(
420
+ _itertools.chain.from_iterable((f'{lib}.1', lib) for lib in lib_filenames),
421
+ )
422
+ elif system == 'Windows':
423
+ bits = 8 * _ctypes.sizeof(_ctypes.c_void_p) # 64 or 32
424
+ lib_filenames = [f'nvcuda{bits}.dll', 'nvcuda.dll']
425
+ # Open library
426
+ for lib_filename in lib_filenames:
427
+ try:
428
+ __cudaLib = _ctypes.CDLL(lib_filename)
429
+ break
430
+ except OSError:
431
+ pass
432
+ if __cudaLib is None:
433
+ _cudaCheckReturn(CUDA_ERROR_NOT_INITIALIZED)
434
+
435
+
436
+ def cuInit(flags: int = 0) -> None:
437
+ """Initialize the CUDA driver API.
438
+
439
+ Initialize the driver API and must be called before any other function from the driver API.
440
+ Currently, the ``flags`` parameter must be :data:`0`. If :func:`cuInit` has not been called,
441
+ any function from the driver API will return :data:`CUDA_ERROR_NOT_INITIALIZED`.
442
+
443
+ Raises:
444
+ CUDAError_NoDevice:
445
+ If no CUDA-capable device is available.
446
+ CUDAError_InvalidDevice:
447
+ If the device ordinal supplied by the user does not correspond to a valid CUDA device or
448
+ that the action requested is invalid for the specified device.
449
+ CUDAError_SystemDriverMismatch:
450
+ If there is a mismatch between the versions of the display driver and the CUDA driver.
451
+ CUDAError_CompatNotSupportedOnDevice:
452
+ If the system was upgraded to run with forward compatibility but the visible hardware
453
+ detected by CUDA does not support this configuration.
454
+ CUDAError_InvalidValue:
455
+ If passed with invalid flag value.
456
+ CUDAError_NotInitialized:
457
+ If cannot found the CUDA driver library.
458
+ """
459
+ global __initialized # pylint: disable=global-statement
460
+
461
+ __LoadCudaLibrary()
462
+
463
+ if __initialized:
464
+ return
465
+
466
+ fn = __cudaGetFunctionPointer('cuInit')
467
+
468
+ ret = fn(_ctypes.c_uint(flags))
469
+ _cudaCheckReturn(ret)
470
+
471
+ with __libLoadLock:
472
+ __initialized = True
473
+
474
+
475
+ def cuGetErrorName(error: int) -> str:
476
+ """Get the string representation of an error code enum name.
477
+
478
+ Raises:
479
+ CUDAError_InvalidValue:
480
+ If the error code is not recognized.
481
+ CUDAError_NotInitialized:
482
+ If the CUDA driver API is not initialized.
483
+ """
484
+ fn = __cudaGetFunctionPointer('cuGetErrorName')
485
+
486
+ p_name = _ctypes.POINTER(_ctypes.c_char_p)()
487
+ ret = fn(_CUresult_t(error), _ctypes.byref(p_name))
488
+ _cudaCheckReturn(ret)
489
+ name = _ctypes.string_at(p_name)
490
+ return name.decode('utf-8', errors='replace')
491
+
492
+
493
+ def cuGetErrorString(error: int) -> str:
494
+ """Get the string description of an error code.
495
+
496
+ Raises:
497
+ CUDAError_InvalidValue:
498
+ If the error code is not recognized.
499
+ CUDAError_NotInitialized:
500
+ If the CUDA driver API is not initialized.
501
+ """
502
+ fn = __cudaGetFunctionPointer('cuGetErrorString')
503
+
504
+ p_name = _ctypes.POINTER(_ctypes.c_char_p)()
505
+ ret = fn(_CUresult_t(error), _ctypes.byref(p_name))
506
+ _cudaCheckReturn(ret)
507
+ name = _ctypes.string_at(p_name)
508
+ return name.decode('utf-8', errors='replace')
509
+
510
+
511
+ def cuDriverGetVersion() -> str:
512
+ """Get the latest CUDA version supported by driver.
513
+
514
+ Returns:
515
+ A string of the form :data:`'<major>.<minor>'`.
516
+
517
+ Raises:
518
+ CUDAError_InvalidValue:
519
+ If the driver call fails.
520
+ CUDAError_NotInitialized:
521
+ If the CUDA driver API is not initialized.
522
+ """
523
+ fn = __cudaGetFunctionPointer('cuDriverGetVersion')
524
+
525
+ driver_version = _ctypes.c_int(0)
526
+ ret = fn(_ctypes.byref(driver_version))
527
+ _cudaCheckReturn(ret)
528
+ major = driver_version.value // 1000
529
+ minor = (driver_version.value % 1000) // 10
530
+ return f'{major}.{minor}'
531
+
532
+
533
+ def cuDeviceGetCount() -> int:
534
+ """Get the number of compute-capable devices.
535
+
536
+ Returns: int
537
+ The number of devices with compute capability greater than or equal to 2.0 that are available
538
+ for execution. If there is no such device, :func:`cuDeviceGetCount` returns :data:`0`.
539
+
540
+ Raises:
541
+ CUDAError_InvalidContext:
542
+ If there is no context bound to the current thread.
543
+ CUDAError_InvalidValue:
544
+ If the driver call fails.
545
+ CUDAError_Deinitialized:
546
+ If the CUDA driver in the process is shutting down.
547
+ CUDAError_NotInitialized:
548
+ If the CUDA driver API is not initialized.
549
+ """
550
+ fn = __cudaGetFunctionPointer('cuDeviceGetCount')
551
+
552
+ count = _ctypes.c_int(0)
553
+ ret = fn(_ctypes.byref(count))
554
+ _cudaCheckReturn(ret)
555
+ return count.value
556
+
557
+
558
+ def cuDeviceGet(ordinal: int) -> _c_CUdevice_t:
559
+ """Get a handle to a compute device.
560
+
561
+ Returns:
562
+ A device handle given an ordinal in the range :code:`[0, ..., cuDeviceGetCount() - 1]`.
563
+
564
+ Raises:
565
+ CUDAError_InvalidContext:
566
+ If there is no context bound to the current thread.
567
+ CUDAError_InvalidDevice:
568
+ If the device ordinal supplied by the user does not correspond to a valid CUDA device or
569
+ that the action requested is invalid for the specified device.
570
+ CUDAError_InvalidValue:
571
+ If the driver call fails.
572
+ CUDAError_Deinitialized:
573
+ If the CUDA driver in the process is shutting down.
574
+ CUDAError_NotInitialized:
575
+ If the CUDA driver API is not initialized.
576
+ """
577
+ fn = __cudaGetFunctionPointer('cuDeviceGet')
578
+
579
+ device = _c_CUdevice_t()
580
+ ret = fn(_ctypes.byref(device), _ctypes.c_int(ordinal))
581
+ _cudaCheckReturn(ret)
582
+ return device
583
+
584
+
585
+ def cuDeviceGetByPCIBusId(pciBusId: str) -> _c_CUdevice_t:
586
+ """Get a handle to a compute device.
587
+
588
+ Args:
589
+ pciBusId (str):
590
+ String in one of the following forms: ``[domain]:[bus]:[device].[function]``,
591
+ ``[domain]:[bus]:[device]``, ``[bus]:[device].[function]`` where ``domain``, ``bus``,
592
+ ``device``, and ``function`` are all hexadecimal values.
593
+
594
+ Returns: int
595
+ A device handle given a PCI bus ID string.
596
+
597
+ Raises:
598
+ CUDAError_InvalidDevice:
599
+ If the device ordinal supplied by the user does not correspond to a valid CUDA device or
600
+ that the action requested is invalid for the specified device.
601
+ CUDAError_InvalidValue:
602
+ If the value of :data:`pciBusId` is not a valid PCI bus identifier.
603
+ CUDAError_Deinitialized:
604
+ If the CUDA driver in the process is shutting down.
605
+ CUDAError_NotInitialized:
606
+ If the CUDA driver API is not initialized.
607
+ """
608
+ fn = __cudaGetFunctionPointer('cuDeviceGetByPCIBusId')
609
+
610
+ device = _c_CUdevice_t()
611
+ ret = fn(_ctypes.byref(device), _ctypes.c_char_p(pciBusId.encode('utf-8')))
612
+ _cudaCheckReturn(ret)
613
+ return device
614
+
615
+
616
+ def cuDeviceGetPCIBusId(device: _c_CUdevice_t) -> str:
617
+ """Get a PCI Bus Id string for the device.
618
+
619
+ Returns: str
620
+ An identifier string for the device in the following format ``[domain]:[bus]:[device].[function]``
621
+ where ``domain``, ``bus``, ``device``, and ``function`` are all hexadecimal values.
622
+
623
+ Raises:
624
+ CUDAError_InvalidDevice:
625
+ If the device ordinal supplied by the user does not correspond to a valid CUDA device or
626
+ that the action requested is invalid for the specified device.
627
+ CUDAError_InvalidValue:
628
+ If the driver call fails.
629
+ CUDAError_Deinitialized:
630
+ If the CUDA driver in the process is shutting down.
631
+ CUDAError_NotInitialized:
632
+ If the CUDA driver API is not initialized.
633
+ """
634
+ fn = __cudaGetFunctionPointer('cuDeviceGetPCIBusId')
635
+
636
+ pciBusId = _ctypes.create_string_buffer(256)
637
+ ret = fn(pciBusId, _ctypes.c_int(256), device)
638
+ _cudaCheckReturn(ret)
639
+ return pciBusId.value.decode('utf-8', errors='replace')
640
+
641
+
642
+ def cuDeviceGetName(device: _c_CUdevice_t) -> str:
643
+ """Get an identifier string for the device.
644
+
645
+ Returns: str
646
+ An ASCII string identifying the device.
647
+
648
+ Raises:
649
+ CUDAError_InvalidContext:
650
+ If there is no context bound to the current thread.
651
+ CUDAError_InvalidDevice:
652
+ If the device ordinal supplied by the user does not correspond to a valid CUDA device or
653
+ that the action requested is invalid for the specified device.
654
+ CUDAError_InvalidValue:
655
+ If the driver call fails.
656
+ CUDAError_Deinitialized:
657
+ If the CUDA driver in the process is shutting down.
658
+ CUDAError_NotInitialized:
659
+ If the CUDA driver API is not initialized.
660
+ """
661
+ fn = __cudaGetFunctionPointer('cuDeviceGetName')
662
+
663
+ name = _ctypes.create_string_buffer(256)
664
+ ret = fn(name, _ctypes.c_int(256), device)
665
+ _cudaCheckReturn(ret)
666
+ return name.value.decode('utf-8', errors='replace')
667
+
668
+
669
+ def cuDeviceGetUuid(device: _c_CUdevice_t) -> str:
670
+ """Get a UUID for the device.
671
+
672
+ Raises:
673
+ CUDAError_InvalidDevice:
674
+ If the device ordinal supplied by the user does not correspond to a valid CUDA device or
675
+ that the action requested is invalid for the specified device.
676
+ CUDAError_InvalidValue:
677
+ If the driver call fails.
678
+ CUDAError_Deinitialized:
679
+ If the CUDA driver in the process is shutting down.
680
+ CUDAError_NotInitialized:
681
+ If the CUDA driver API is not initialized.
682
+ """
683
+ try:
684
+ fn = __cudaGetFunctionPointer('cuDeviceGetUuid_v2')
685
+ except CUDAError_NotFound: # noqa: F821 # pylint: disable=undefined-variable
686
+ fn = __cudaGetFunctionPointer('cuDeviceGetUuid')
687
+
688
+ uuid = (_ctypes.c_ubyte * 16)()
689
+ ret = fn(uuid, device)
690
+ _cudaCheckReturn(ret)
691
+ uuid = ''.join(map('{:02x}'.format, uuid))
692
+ return '-'.join((uuid[:8], uuid[8:12], uuid[12:16], uuid[16:20], uuid[20:32]))
693
+
694
+
695
+ def cuDeviceGetUuid_v2(device: _c_CUdevice_t) -> str:
696
+ """Get a UUID for the device (CUDA 11.4+).
697
+
698
+ Raises:
699
+ CUDAError_InvalidDevice:
700
+ If the device ordinal supplied by the user does not correspond to a valid CUDA device or
701
+ that the action requested is invalid for the specified device.
702
+ CUDAError_InvalidValue:
703
+ If the driver call fails.
704
+ CUDAError_Deinitialized:
705
+ If the CUDA driver in the process is shutting down.
706
+ CUDAError_NotInitialized:
707
+ If the CUDA driver API is not initialized.
708
+ """
709
+ fn = __cudaGetFunctionPointer('cuDeviceGetUuid_v2')
710
+
711
+ uuid = (_ctypes.c_ubyte * 16)()
712
+ ret = fn(uuid, device)
713
+ _cudaCheckReturn(ret)
714
+ uuid = ''.join(map('{:02x}'.format, uuid))
715
+ return '-'.join((uuid[:8], uuid[8:12], uuid[12:16], uuid[16:20], uuid[20:32]))
716
+
717
+
718
+ def cuDeviceTotalMem(device: _c_CUdevice_t) -> int:
719
+ """Get the total amount of memory on the device (in bytes).
720
+
721
+ Raises:
722
+ CUDAError_InvalidContext:
723
+ If there is no context bound to the current thread.
724
+ CUDAError_InvalidDevice:
725
+ If the device ordinal supplied by the user does not correspond to a valid CUDA device or
726
+ that the action requested is invalid for the specified device.
727
+ CUDAError_InvalidValue:
728
+ If the driver call fails.
729
+ CUDAError_Deinitialized:
730
+ If the CUDA driver in the process is shutting down.
731
+ CUDAError_NotInitialized:
732
+ If the CUDA driver API is not initialized.
733
+ """
734
+ fn = __cudaGetFunctionPointer('cuDeviceTotalMem')
735
+
736
+ bytes = _ctypes.c_size_t(0) # pylint: disable=redefined-builtin
737
+ ret = fn(_ctypes.byref(bytes), device)
738
+ _cudaCheckReturn(ret)
739
+ return bytes.value
740
+
741
+
742
+ def is_available() -> bool:
743
+ """Test whether there are any CUDA visible devices."""
744
+ try:
745
+ return cuDeviceGetCount() > 0
746
+ except CUDAError:
747
+ return False
.venv/lib/python3.10/site-packages/nvitop/api/libcudart.py ADDED
@@ -0,0 +1,735 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is part of nvitop, the interactive NVIDIA-GPU process viewer.
2
+ #
3
+ # Copyright 2021-2025 Xuehai Pan. All Rights Reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ # ==============================================================================
17
+ """Python bindings for the `CUDA Runtime APIs <https://docs.nvidia.com/cuda/cuda-runtime-api>`_."""
18
+
19
+ # pylint: disable=invalid-name
20
+
21
+ from __future__ import annotations
22
+
23
+ import ctypes as _ctypes
24
+ import glob as _glob
25
+ import os as _os
26
+ import platform as _platform
27
+ import sys as _sys
28
+ import threading as _threading
29
+ from typing import TYPE_CHECKING as _TYPE_CHECKING
30
+ from typing import Any as _Any
31
+ from typing import ClassVar as _ClassVar
32
+
33
+
34
+ if _TYPE_CHECKING:
35
+ from collections.abc import Callable as _Callable
36
+ from typing_extensions import Self as _Self # Python 3.11+
37
+
38
+
39
+ _cudaError_t = _ctypes.c_int
40
+
41
+ # Error codes #
42
+ # pylint: disable=line-too-long
43
+ cudaSuccess = 0
44
+ """The API call returned with no errors. In the case of query calls, this also means that the operation being queried is complete (see :func:`cudaEventQuery` and :func:`cudaStreamQuery`)."""
45
+ cudaErrorInvalidValue = 1
46
+ """This indicates that one or more of the parameters passed to the API call is not within an acceptable range of values."""
47
+ cudaErrorMemoryAllocation = 2
48
+ """The API call failed because it was unable to allocate enough memory to perform the requested operation."""
49
+ cudaErrorInitializationError = 3
50
+ """The API call failed because the CUDA driver and runtime could not be initialized."""
51
+ cudaErrorCudartUnloading = 4
52
+ """This indicates that a CUDA Runtime API call cannot be executed because it is being called during process shut down, at a point in time after CUDA driver has been unloaded."""
53
+ cudaErrorProfilerDisabled = 5
54
+ """This indicates profiler is not initialized for this run. This can happen when the application is running with external profiling tools like visual profiler."""
55
+ cudaErrorInvalidConfiguration = 9
56
+ """This indicates that a kernel launch is requesting resources that can never be satisfied by the current device. Requesting more shared memory per block than the device supports will trigger this error, as will requesting too many threads or blocks. See cudaDeviceProp for more device limitations."""
57
+ cudaErrorInvalidPitchValue = 12
58
+ """This indicates that one or more of the pitch-related parameters passed to the API call is not within the acceptable range for pitch."""
59
+ cudaErrorInvalidSymbol = 13
60
+ """This indicates that the symbol name / identifier passed to the API call is not a valid name or identifier."""
61
+ cudaErrorInvalidTexture = 18
62
+ """This indicates that the texture passed to the API call is not a valid texture."""
63
+ cudaErrorInvalidTextureBinding = 19
64
+ """This indicates that the texture binding is not valid. This occurs if you call :func:`cudaGetTextureAlignmentOffset` with an unbound texture."""
65
+ cudaErrorInvalidChannelDescriptor = 20
66
+ """This indicates that the channel descriptor passed to the API call is not valid. This occurs if the format is not one of the formats specified by :data:`cudaChannelFormatKind`, or if one of the dimensions is invalid."""
67
+ cudaErrorInvalidMemcpyDirection = 21
68
+ """This indicates that the direction of the :func:`memcpy` passed to the API call is not one of the types specified by :data:`cudaMemcpyKind`."""
69
+ cudaErrorInvalidFilterSetting = 26
70
+ """This indicates that a non-float texture was being accessed with linear filtering. This is not supported by CUDA."""
71
+ cudaErrorInvalidNormSetting = 27
72
+ """This indicates that an attempt was made to read a non-float texture as a normalized float. This is not supported by CUDA."""
73
+ cudaErrorStubLibrary = 34
74
+ """This indicates that the CUDA driver that the application has loaded is a stub library. Applications that run with the stub rather than a real driver loaded will result in CUDA API returning this error."""
75
+ cudaErrorInsufficientDriver = 35
76
+ """This indicates that the installed NVIDIA CUDA driver is older than the CUDA Runtime library. This is not a supported configuration. Users should install an updated NVIDIA display driver to allow the application to run."""
77
+ cudaErrorCallRequiresNewerDriver = 36
78
+ """This indicates that the API call requires a newer CUDA driver than the one currently installed. Users should install an updated NVIDIA CUDA driver to allow the API call to succeed."""
79
+ cudaErrorInvalidSurface = 37
80
+ """This indicates that the surface passed to the API call is not a valid surface."""
81
+ cudaErrorDuplicateVariableName = 43
82
+ """This indicates that multiple global or constant variables (across separate CUDA source files in the application) share the same string name."""
83
+ cudaErrorDuplicateTextureName = 44
84
+ """This indicates that multiple textures (across separate CUDA source files in the application) share the same string name."""
85
+ cudaErrorDuplicateSurfaceName = 45
86
+ """This indicates that multiple surfaces (across separate CUDA source files in the application) share the same string name."""
87
+ cudaErrorDevicesUnavailable = 46
88
+ """This indicates that all CUDA devices are busy or unavailable at the current time. Devices are often busy / unavailable due to use of :data:`cudaComputeModeProhibited`, :data:`cudaComputeModeExclusiveProcess`, or when long running CUDA kernels have filled up the GPU and are blocking new work from starting. They can also be unavailable due to memory constraints on a device that already has active CUDA work being performed."""
89
+ cudaErrorIncompatibleDriverContext = 49
90
+ """This indicates that the current context is not compatible with this the CUDA Runtime. This can only occur if you are using CUDA Runtime / Driver interoperability and have created an existing Driver context using the driver API. The Driver context may be incompatible either because the Driver context was created using an older version of the API, because the Runtime API call expects a primary driver context and the Driver context is not primary, or because the Driver context has been destroyed."""
91
+ cudaErrorMissingConfiguration = 52
92
+ """The device function being invoked (usually via :func:`cudaLaunchKernel`) was not previously configured via the :func:`cudaConfigureCall` function."""
93
+ cudaErrorLaunchMaxDepthExceeded = 65
94
+ """This error indicates that a device runtime grid launch did not occur because the depth of the child grid would exceed the maximum supported number of nested grid launches."""
95
+ cudaErrorLaunchFileScopedTex = 66
96
+ """This error indicates that a grid launch did not occur because the kernel uses file-scoped textures which are unsupported by the device runtime. Kernels launched via the device runtime only support textures created with the Texture Object API's."""
97
+ cudaErrorLaunchFileScopedSurf = 67
98
+ """This error indicates that a grid launch did not occur because the kernel uses file-scoped surfaces which are unsupported by the device runtime. Kernels launched via the device runtime only support surfaces created with the Surface Object API's."""
99
+ cudaErrorSyncDepthExceeded = 68
100
+ """This error indicates that a call to :func:`cudaDeviceSynchronize` made from the device runtime failed because the call was made at grid depth greater than than either the default (2 levels of grids) or user specified device limit :data:`cudaLimitDevRuntimeSyncDepth`. To be able to synchronize on launched grids at a greater depth successfully, the maximum nested depth at which :func:`cudaDeviceSynchronize` will be called must be specified with the :data:`cudaLimitDevRuntimeSyncDepth` limit to the :func:`cudaDeviceSetLimit` api before the host-side launch of a kernel using the device runtime. Keep in mind that additional levels of sync depth require the runtime to reserve large amounts of device memory that cannot be used for user allocations. Note that :func:`cudaDeviceSynchronize` made from device runtime is only supported on devices of compute capability < 9.0."""
101
+ cudaErrorLaunchPendingCountExceeded = 69
102
+ """This error indicates that a device runtime grid launch failed because the launch would exceed the limit :data:`cudaLimitDevRuntimePendingLaunchCount`. For this launch to proceed successfully, :func:`cudaDeviceSetLimit` must be called to set the :data:`cudaLimitDevRuntimePendingLaunchCount` to be higher than the upper bound of outstanding launches that can be issued to the device runtime. Keep in mind that raising the limit of pending device runtime launches will require the runtime to reserve device memory that cannot be used for user allocations."""
103
+ cudaErrorInvalidDeviceFunction = 98
104
+ """The requested device function does not exist or is not compiled for the proper device architecture."""
105
+ cudaErrorNoDevice = 100
106
+ """This indicates that no CUDA-capable devices were detected by the installed CUDA driver."""
107
+ cudaErrorInvalidDevice = 101
108
+ """This indicates that the device ordinal supplied by the user does not correspond to a valid CUDA device or that the action requested is invalid for the specified device."""
109
+ cudaErrorDeviceNotLicensed = 102
110
+ """This indicates that the device doesn't have a valid Grid License."""
111
+ cudaErrorSoftwareValidityNotEstablished = 103
112
+ """By default, the CUDA Runtime may perform a minimal set of self-tests, as well as CUDA driver tests, to establish the validity of both. Introduced in CUDA 11.2, this error return indicates that at least one of these tests has failed and the validity of either the runtime or the driver could not be established."""
113
+ cudaErrorStartupFailure = 127
114
+ """This indicates an internal startup failure in the CUDA Runtime."""
115
+ cudaErrorInvalidKernelImage = 200
116
+ """This indicates that the device kernel image is invalid."""
117
+ cudaErrorDeviceUninitialized = 201
118
+ """This most frequently indicates that there is no context bound to the current thread. This can also be returned if the context passed to an API call is not a valid handle (such as a context that has had :func`cuCtxDestroy` invoked on it). This can also be returned if a user mixes different API versions (i.e. 3010 context with 3020 API calls)."""
119
+ cudaErrorMapBufferObjectFailed = 205
120
+ """This indicates that the buffer object could not be mapped."""
121
+ cudaErrorUnmapBufferObjectFailed = 206
122
+ """This indicates that the buffer object could not be unmapped."""
123
+ cudaErrorArrayIsMapped = 207
124
+ """This indicates that the specified array is currently mapped and thus cannot be destroyed."""
125
+ cudaErrorAlreadyMapped = 208
126
+ """This indicates that the resource is already mapped."""
127
+ cudaErrorNoKernelImageForDevice = 209
128
+ """This indicates that there is no kernel image available that is suitable for the device. This can occur when a user specifies code generation options for a particular CUDA source file that do not include the corresponding device configuration."""
129
+ cudaErrorAlreadyAcquired = 210
130
+ """This indicates that a resource has already been acquired."""
131
+ cudaErrorNotMapped = 211
132
+ """This indicates that a resource is not mapped."""
133
+ cudaErrorNotMappedAsArray = 212
134
+ """This indicates that a mapped resource is not available for access as an array."""
135
+ cudaErrorNotMappedAsPointer = 213
136
+ """This indicates that a mapped resource is not available for access as a pointer."""
137
+ cudaErrorECCUncorrectable = 214
138
+ """This indicates that an uncorrectable ECC error was detected during execution."""
139
+ cudaErrorUnsupportedLimit = 215
140
+ """This indicates that the :class:`cudaLimit` passed to the API call is not supported by the active device."""
141
+ cudaErrorDeviceAlreadyInUse = 216
142
+ """This indicates that a call tried to access an exclusive-thread device that is already in use by a different thread."""
143
+ cudaErrorPeerAccessUnsupported = 217
144
+ """This error indicates that P2P access is not supported across the given devices."""
145
+ cudaErrorInvalidPtx = 218
146
+ """A PTX compilation failed. The runtime may fall back to compiling PTX if an application does not contain a suitable binary for the current device."""
147
+ cudaErrorInvalidGraphicsContext = 219
148
+ """This indicates an error with the OpenGL or DirectX context."""
149
+ cudaErrorNvlinkUncorrectable = 220
150
+ """This indicates that an uncorrectable NVLink error was detected during the execution."""
151
+ cudaErrorJitCompilerNotFound = 221
152
+ """This indicates that the PTX JIT compiler library was not found. The JIT Compiler library is used for PTX compilation. The runtime may fall back to compiling PTX if an application does not contain a suitable binary for the current device."""
153
+ cudaErrorUnsupportedPtxVersion = 222
154
+ """This indicates that the provided PTX was compiled with an unsupported toolchain. The most common reason for this, is the PTX was generated by a compiler newer than what is supported by the CUDA driver and PTX JIT compiler."""
155
+ cudaErrorJitCompilationDisabled = 223
156
+ """This indicates that the JIT compilation was disabled. The JIT compilation compiles PTX. The runtime may fall back to compiling PTX if an application does not contain a suitable binary for the current device."""
157
+ cudaErrorUnsupportedExecAffinity = 224
158
+ """This indicates that the provided execution affinity is not supported by the device."""
159
+ cudaErrorInvalidSource = 300
160
+ """This indicates that the device kernel source is invalid."""
161
+ cudaErrorFileNotFound = 301
162
+ """This indicates that the file specified was not found."""
163
+ cudaErrorSharedObjectSymbolNotFound = 302
164
+ """This indicates that a link to a shared object failed to resolve."""
165
+ cudaErrorSharedObjectInitFailed = 303
166
+ """This indicates that initialization of a shared object failed."""
167
+ cudaErrorOperatingSystem = 304
168
+ """This error indicates that an OS call failed."""
169
+ cudaErrorInvalidResourceHandle = 400
170
+ """This indicates that a resource handle passed to the API call was not valid. Resource handles are opaque types like :data:`cudaStream_t` and :data:`cudaEvent_t`."""
171
+ cudaErrorIllegalState = 401
172
+ """This indicates that a resource required by the API call is not in a valid state to perform the requested operation."""
173
+ cudaErrorSymbolNotFound = 500
174
+ """This indicates that a named symbol was not found. Examples of symbols are global / constant variable names, driver function names, texture names, and surface names."""
175
+ cudaErrorNotReady = 600
176
+ """This indicates that asynchronous operations issued previously have not completed yet. This result is not actually an error, but must be indicated differently than :data:`cudaSuccess` (which indicates completion). Calls that may return this value include :func:`cudaEventQuery` and :func:`cudaStreamQuery`."""
177
+ cudaErrorIllegalAddress = 700
178
+ """The device encountered a load or store instruction on an invalid memory address. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched."""
179
+ cudaErrorLaunchOutOfResources = 701
180
+ """This indicates that a launch did not occur because it did not have appropriate resources. Although this error is similar to :data:`cudaErrorInvalidConfiguration`, this error usually indicates that the user has attempted to pass too many arguments to the device kernel, or the kernel launch specifies too many threads for the kernel's register count."""
181
+ cudaErrorLaunchTimeout = 702
182
+ """This indicates that the device kernel took too long to execute. This can only occur if timeouts are enabled - see the device property kernelExecTimeoutEnabled for more information. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched."""
183
+ cudaErrorLaunchIncompatibleTexturing = 703
184
+ """This error indicates a kernel launch that uses an incompatible texturing mode."""
185
+ cudaErrorPeerAccessAlreadyEnabled = 704
186
+ """This error indicates that a call to :func:`cudaDeviceEnablePeerAccess` is trying to re-enable peer addressing on from a context which has already had peer addressing enabled."""
187
+ cudaErrorPeerAccessNotEnabled = 705
188
+ """This error indicates that :func:`cudaDeviceDisablePeerAccess` is trying to disable peer addressing which has not been enabled yet via :func:`cudaDeviceEnablePeerAccess`."""
189
+ cudaErrorSetOnActiveProcess = 708
190
+ """This indicates that the user has called :func:`cudaSetValidDevices`, :func:`cudaSetDeviceFlags`, :func:`cudaD3D9SetDirect3DDevice`, :func:`cudaD3D10SetDirect3DDevice`, :func:`cudaD3D11SetDirect3DDevice`, or :func:`cudaVDPAUSetVDPAUDevice` after initializing the CUDA Runtime by calling non-device management operations (allocating memory and launching kernels are examples of non-device management operations). This error can also be returned if using runtime / driver interoperability and there is an existing :class:`CUcontext` active on the host thread."""
191
+ cudaErrorContextIsDestroyed = 709
192
+ """This error indicates that the context current to the calling thread has been destroyed using cuCtxDestroy, or is a primary context which has not yet been initialized."""
193
+ cudaErrorAssert = 710
194
+ """An assert triggered in device code during kernel execution. The device cannot be used again. All existing allocations are invalid. To continue using CUDA, the process must be terminated and relaunched."""
195
+ cudaErrorTooManyPeers = 711
196
+ """This error indicates that the hardware resources required to enable peer access have been exhausted for one or more of the devices passed to :func:`cudaEnablePeerAccess`."""
197
+ cudaErrorHostMemoryAlreadyRegistered = 712
198
+ """This error indicates that the memory range passed to :func:`cudaHostRegister` has already been registered."""
199
+ cudaErrorHostMemoryNotRegistered = 713
200
+ """This error indicates that the pointer passed to :func:`cudaHostUnregister` does not correspond to any currently registered memory region."""
201
+ cudaErrorHardwareStackError = 714
202
+ """Device encountered an error in the call stack during kernel execution, possibly due to stack corruption or exceeding the stack size limit. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched."""
203
+ cudaErrorIllegalInstruction = 715
204
+ """The device encountered an illegal instruction during kernel execution This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched."""
205
+ cudaErrorMisalignedAddress = 716
206
+ """The device encountered a load or store instruction on a memory address which is not aligned. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched."""
207
+ cudaErrorInvalidAddressSpace = 717
208
+ """While executing a kernel, the device encountered an instruction which can only operate on memory locations in certain address spaces (global, shared, or local), but was supplied a memory address not belonging to an allowed address space. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched."""
209
+ cudaErrorInvalidPc = 718
210
+ """The device encountered an invalid program counter. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched."""
211
+ cudaErrorLaunchFailure = 719
212
+ """An exception occurred on the device while executing a kernel. Common causes include dereferencing an invalid device pointer and accessing out of bounds shared memory. Less common cases can be system specific - more information about these cases can be found in the system specific user guide. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched."""
213
+ cudaErrorCooperativeLaunchTooLarge = 720
214
+ """This error indicates that the number of blocks launched per grid for a kernel that was launched via either :func:`cudaLaunchCooperativeKernel` or :func:`cudaLaunchCooperativeKernelMultiDevice` exceeds the maximum number of blocks as allowed by :func:`cudaOccupancyMaxActiveBlocksPerMultiprocessor` or :func:`cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags` times the number of multiprocessors as specified by the device attribute :func:`cudaDevAttrMultiProcessorCount`."""
215
+ cudaErrorNotPermitted = 800
216
+ """This error indicates the attempted operation is not permitted."""
217
+ cudaErrorNotSupported = 801
218
+ """This error indicates the attempted operation is not supported on the current system or device."""
219
+ cudaErrorSystemNotReady = 802
220
+ """This error indicates that the system is not yet ready to start any CUDA work. To continue using CUDA, verify the system configuration is in a valid state and all required driver daemons are actively running. More information about this error can be found in the system specific user guide."""
221
+ cudaErrorSystemDriverMismatch = 803
222
+ """This error indicates that there is a mismatch between the versions of the display driver and the CUDA driver. Refer to the compatibility documentation for supported versions."""
223
+ cudaErrorCompatNotSupportedOnDevice = 804
224
+ """This error indicates that the system was upgraded to run with forward compatibility but the visible hardware detected by CUDA does not support this configuration. Refer to the compatibility documentation for the supported hardware matrix or ensure that only supported hardware is visible during initialization via the ``CUDA_VISIBLE_DEVICES`` environment variable."""
225
+ cudaErrorMpsConnectionFailed = 805
226
+ """This error indicates that the MPS client failed to connect to the MPS control daemon or the MPS server."""
227
+ cudaErrorMpsRpcFailure = 806
228
+ """This error indicates that the remote procedural call between the MPS server and the MPS client failed."""
229
+ cudaErrorMpsServerNotReady = 807
230
+ """This error indicates that the MPS server is not ready to accept new MPS client requests. This error can be returned when the MPS server is in the process of recovering from a fatal failure."""
231
+ cudaErrorMpsMaxClientsReached = 808
232
+ """This error indicates that the hardware resources required to create MPS client have been exhausted."""
233
+ cudaErrorMpsMaxConnectionsReached = 809
234
+ """This error indicates the the hardware resources required to device connections have been exhausted."""
235
+ cudaErrorMpsClientTerminated = 810
236
+ """This error indicates that the MPS client has been terminated by the server. To continue using CUDA, the process must be terminated and relaunched."""
237
+ cudaErrorCdpNotSupported = 811
238
+ """This error indicates, that the program is using CUDA Dynamic Parallelism, but the current configuration, like MPS, does not support it."""
239
+ cudaErrorCdpVersionMismatch = 812
240
+ """This error indicates, that the program contains an unsupported interaction between different versions of CUDA Dynamic Parallelism."""
241
+ cudaErrorStreamCaptureUnsupported = 900
242
+ """The operation is not permitted when the stream is capturing."""
243
+ cudaErrorStreamCaptureInvalidated = 901
244
+ """The current capture sequence on the stream has been invalidated due to a previous error."""
245
+ cudaErrorStreamCaptureMerge = 902
246
+ """The operation would have resulted in a merge of two independent capture sequences."""
247
+ cudaErrorStreamCaptureUnmatched = 903
248
+ """The capture was not initiated in this stream."""
249
+ cudaErrorStreamCaptureUnjoined = 904
250
+ """The capture sequence contains a fork that was not joined to the primary stream."""
251
+ cudaErrorStreamCaptureIsolation = 905
252
+ """A dependency would have been created which crosses the capture sequence boundary. Only implicit in-stream ordering dependencies are allowed to cross the boundary."""
253
+ cudaErrorStreamCaptureImplicit = 906
254
+ """The operation would have resulted in a disallowed implicit dependency on a current capture sequence from :data:`cudaStreamLegacy`."""
255
+ cudaErrorCapturedEvent = 907
256
+ """The operation is not permitted on an event which was last recorded in a capturing stream."""
257
+ cudaErrorStreamCaptureWrongThread = 908
258
+ """A stream capture sequence not initiated with the :data:`cudaStreamCaptureModeRelaxed` argument to :func:`cudaStreamBeginCapture` was passed to :func:`cudaStreamEndCapture` in a different thread."""
259
+ cudaErrorTimeout = 909
260
+ """This indicates that the wait operation has timed out."""
261
+ cudaErrorGraphExecUpdateFailure = 910
262
+ """This error indicates that the graph update was not performed because it included changes which violated constraints specific to instantiated graph update."""
263
+ cudaErrorExternalDevice = 911
264
+ """This indicates that an async error has occurred in a device outside of CUDA. If CUDA was waiting for an external device's signal before consuming shared data, the external device signaled an error indicating that the data is not valid for consumption. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched."""
265
+ cudaErrorInvalidClusterSize = 912
266
+ """This indicates that a kernel launch error has occurred due to cluster misconfiguration."""
267
+ cudaErrorUnknown = 999
268
+ """This indicates that an unknown internal error has occurred."""
269
+ # pylint: enable=line-too-long
270
+
271
+
272
+ # Error Checking #
273
+ class cudaError(Exception):
274
+ """Base exception class for CUDA driver query errors."""
275
+
276
+ _value_class_mapping: _ClassVar[dict[int, type[cudaError]]] = {}
277
+ _errcode_to_string: _ClassVar[dict[int, str]] = { # List of currently known error codes
278
+ cudaErrorInitializationError: 'Initialization error.',
279
+ cudaErrorSymbolNotFound: 'Named symbol not found.',
280
+ cudaErrorInvalidValue: 'Invalid argument.',
281
+ cudaErrorNoDevice: 'No CUDA-capable device is detected.',
282
+ cudaErrorInvalidDevice: 'Invalid device ordinal.',
283
+ cudaErrorSystemDriverMismatch: 'System has unsupported display driver / CUDA driver combination.',
284
+ cudaErrorCudartUnloading: 'Driver shutting down.',
285
+ cudaErrorCompatNotSupportedOnDevice: 'Forward compatibility was attempted on non supported Hardware.',
286
+ cudaErrorDeviceUninitialized: 'Invalid device context.',
287
+ } # fmt:skip
288
+ _errcode_to_name: _ClassVar[dict[int, str]] = {}
289
+ value: int
290
+
291
+ def __new__(cls, value: int) -> _Self:
292
+ """Map value to a proper subclass of :class:`cudaError`."""
293
+ if cls is cudaError:
294
+ # pylint: disable-next=self-cls-assignment
295
+ cls = cudaError._value_class_mapping.get(value, cls) # type: ignore[assignment]
296
+ obj = Exception.__new__(cls)
297
+ obj.value = value
298
+ return obj
299
+
300
+ def __repr__(self) -> str:
301
+ """Return a string representation of the error."""
302
+ # pylint: disable=no-member
303
+ try:
304
+ if self.value not in cudaError._errcode_to_string:
305
+ cudaError._errcode_to_string[self.value] = '{}.'.format(
306
+ cuGetErrorString(self.value).rstrip('.').capitalize(),
307
+ )
308
+ if self.value not in cudaError._errcode_to_name:
309
+ cudaError._errcode_to_name[self.value] = cudaGetErrorName(self.value)
310
+ return (
311
+ f'{cudaError._errcode_to_string[self.value]} '
312
+ f'Code: {cudaError._errcode_to_name[self.value]} ({self.value}).'
313
+ )
314
+ except cudaError:
315
+ return f'CUDA Error with code {self.value}.'
316
+
317
+ def __eq__(self, other: object) -> bool:
318
+ """Test equality to other object."""
319
+ if not isinstance(other, cudaError):
320
+ return NotImplemented
321
+ return self.value == other.value # pylint: disable=no-member
322
+
323
+ def __reduce__(self) -> tuple[type[cudaError], tuple[int]]:
324
+ """Return state information for pickling."""
325
+ return cudaError, (self.value,) # pylint: disable=no-member
326
+
327
+
328
+ def cudaExceptionClass(cudaErrorCode: int, /) -> type[cudaError]:
329
+ """Map value to a proper subclass of :class:`cudaError`.
330
+
331
+ Raises:
332
+ ValueError: If the error code is not valid.
333
+ """
334
+ if cudaErrorCode not in cudaError._value_class_mapping: # pylint: disable=protected-access
335
+ raise ValueError(f'cudaErrorCode {cudaErrorCode} is not valid.')
336
+ return cudaError._value_class_mapping[cudaErrorCode] # pylint: disable=protected-access
337
+
338
+
339
+ def _extract_cuda_errors_as_classes() -> None:
340
+ """Generate a hierarchy of classes on top of :class:`cudaError` class.
341
+
342
+ Each CUDA Error gets a new :class:`cudaError` subclass. This way try-except blocks can filter
343
+ appropriate exceptions more easily.
344
+
345
+ :class:`cudaError` is a parent class. Each ``cudaError*`` gets it's own subclass.
346
+ e.g. :data:`cudaErrorInvalidValue` will be turned into :class:`cudaError_InvalidValue`.
347
+ """
348
+ this_module = _sys.modules[__name__]
349
+ cuda_error_names = [
350
+ x
351
+ for x in dir(this_module)
352
+ if x.startswith('cudaError') and not x.startswith('cudaError_') and x != 'cudaError'
353
+ ]
354
+ for err_name in cuda_error_names:
355
+ # e.g. Turn cudaErrorInvalidValue into cudaError_InvalidValue
356
+ class_name = err_name.replace('cudaError', 'cudaError_')
357
+ err_val = getattr(this_module, err_name)
358
+
359
+ def gen_new(value: int) -> _Callable[[type[cudaError]], cudaError]:
360
+ def new(cls: type[cudaError]) -> cudaError:
361
+ return cudaError.__new__(cls, value)
362
+
363
+ return new
364
+
365
+ # pylint: disable=protected-access
366
+ new_error_class = type(class_name, (cudaError,), {'__new__': gen_new(err_val)})
367
+ new_error_class.__module__ = __name__
368
+ if err_val in cudaError._errcode_to_string:
369
+ new_error_class.__doc__ = (
370
+ f'cudaError: {cudaError._errcode_to_string[err_val]} '
371
+ f'Code: :data:`{err_name}` ({err_val}).'
372
+ )
373
+ else:
374
+ new_error_class.__doc__ = f'CUDA Error with code :data:`{err_name}` ({err_val})'
375
+ setattr(this_module, class_name, new_error_class)
376
+ cudaError._value_class_mapping[err_val] = new_error_class
377
+ cudaError._errcode_to_name[err_val] = err_name
378
+
379
+
380
+ # Add explicit references to appease linters
381
+ class __cudaError(cudaError):
382
+ value: int
383
+
384
+ def __new__(cls) -> cudaError: # type: ignore[misc,empty-body]
385
+ ...
386
+
387
+
388
+ cudaError_InitializationError: type[__cudaError]
389
+ cudaError_SymbolNotFound: type[__cudaError]
390
+ cudaError_InvalidValue: type[__cudaError]
391
+ cudaError_NoDevice: type[__cudaError]
392
+ cudaError_InvalidDevice: type[__cudaError]
393
+ cudaError_SystemDriverMismatch: type[__cudaError]
394
+ cudaError_CudartUnloading: type[__cudaError]
395
+ cudaError_CompatNotSupportedOnDevice: type[__cudaError]
396
+ cudaError_DeviceUninitialized: type[__cudaError]
397
+
398
+ _extract_cuda_errors_as_classes()
399
+ del _extract_cuda_errors_as_classes
400
+
401
+
402
+ def _cudaCheckReturn(ret: _Any, /) -> _Any:
403
+ if ret != cudaSuccess:
404
+ raise cudaError(ret)
405
+ return ret
406
+
407
+
408
+ # Function access #
409
+ __cudaLib: _ctypes.CDLL | None = None
410
+ __libLoadLock: _threading.Lock = _threading.Lock()
411
+ # Function pointers are cached to prevent unnecessary libLoadLock locking
412
+ __cudaGetFunctionPointer_cache: dict[str, _ctypes._CFuncPtr] = {} # type: ignore[name-defined]
413
+
414
+
415
+ def __cudaGetFunctionPointer(name: str, /) -> _ctypes._CFuncPtr: # type: ignore[name-defined]
416
+ """Get the function pointer from the CUDA Runtime library.
417
+
418
+ Raises:
419
+ cudaError_InitializationError:
420
+ If cannot found the CUDA Runtime library.
421
+ cudaError_SymbolNotFound:
422
+ If cannot found the function pointer.
423
+ """
424
+ if name in __cudaGetFunctionPointer_cache:
425
+ return __cudaGetFunctionPointer_cache[name]
426
+
427
+ if __cudaLib is None:
428
+ __LoadCudaLibrary()
429
+
430
+ with __libLoadLock:
431
+ try:
432
+ __cudaGetFunctionPointer_cache[name] = getattr(__cudaLib, name)
433
+ return __cudaGetFunctionPointer_cache[name]
434
+ except AttributeError as ex:
435
+ raise cudaError(cudaErrorSymbolNotFound) from ex
436
+
437
+
438
+ def __LoadCudaLibrary() -> None: # pylint: disable=too-many-branches
439
+ """Load the library if it isn't loaded already.
440
+
441
+ Raises:
442
+ cudaError_InitializationError:
443
+ If cannot found the CUDA Runtime library.
444
+ """
445
+ global __cudaLib # pylint: disable=global-statement
446
+
447
+ if __cudaLib is None:
448
+ # Lock to ensure only one caller loads the library
449
+ with __libLoadLock:
450
+ # Ensure the library still isn't loaded
451
+ if __cudaLib is None: # pylint: disable=too-many-nested-blocks
452
+ # Platform specific libcudart location
453
+ system = _platform.system()
454
+ bits = 8 * _ctypes.sizeof(_ctypes.c_void_p) # 64 or 32
455
+ if system == 'Darwin':
456
+ lib_filenames = ['libcudart.dylib']
457
+ elif system == 'Linux':
458
+ lib_filenames = ['libcudart.so']
459
+ elif system == 'Windows':
460
+ lib_filenames = [f'cudart{bits}.dll', 'cudart.dll']
461
+ else:
462
+ lib_filenames = []
463
+
464
+ # Open library
465
+ for lib_filename in lib_filenames:
466
+ try:
467
+ __cudaLib = _ctypes.CDLL(lib_filename)
468
+ break
469
+ except OSError:
470
+ pass
471
+
472
+ # Try to load the library from the CUDA_PATH environment variable
473
+ if __cudaLib is None:
474
+ cuda_paths = [
475
+ _os.getenv(env_name, '')
476
+ for env_name in ('CUDA_PATH', 'CUDA_HOME', 'CUDA_ROOT')
477
+ ]
478
+ if system != 'Windows':
479
+ cuda_paths.append('/usr/local/cuda')
480
+ candidate_paths = []
481
+ for cuda_path in cuda_paths:
482
+ if _os.path.isdir(cuda_path):
483
+ for lib_filename in lib_filenames:
484
+ candidate_paths.extend(
485
+ [
486
+ _os.path.join(cuda_path, f'lib{bits}', lib_filename),
487
+ _os.path.join(cuda_path, 'lib', lib_filename),
488
+ ],
489
+ )
490
+ else:
491
+ candidate_dirs = _os.getenv('PATH', '').split(_os.path.pathsep)
492
+ candidate_paths = []
493
+ for cuda_path in cuda_paths:
494
+ if _os.path.isdir(cuda_path):
495
+ candidate_dirs.extend(
496
+ [
497
+ _os.path.join(cuda_path, 'bin'),
498
+ _os.path.join(cuda_path, f'lib{bits}'),
499
+ _os.path.join(cuda_path, 'lib'),
500
+ ],
501
+ )
502
+ for candidate_dir in candidate_dirs:
503
+ candidate_paths.extend(
504
+ _glob.iglob(_os.path.join(candidate_dir, f'cudart{bits}*.dll')),
505
+ )
506
+
507
+ # Normalize paths and remove duplicates
508
+ candidate_paths = list(
509
+ dict.fromkeys(
510
+ _os.path.normpath(_os.path.normcase(p)) for p in candidate_paths
511
+ ),
512
+ )
513
+ for lib_filename in candidate_paths:
514
+ try:
515
+ __cudaLib = _ctypes.CDLL(lib_filename)
516
+ break
517
+ except OSError:
518
+ pass
519
+
520
+ if __cudaLib is None:
521
+ _cudaCheckReturn(cudaErrorInitializationError)
522
+
523
+
524
+ def cudaGetErrorName(error: int) -> str:
525
+ """Get the string representation of an error code enum name.
526
+
527
+ Returns: str
528
+ A string containing the name of an error code in the enum. If the error code is not
529
+ recognized, "unrecognized error code" is returned.
530
+
531
+ Raises:
532
+ cudaError_InitializationError:
533
+ If cannot found the CUDA Runtime library.
534
+ """
535
+ fn = __cudaGetFunctionPointer('cudaGetErrorName')
536
+
537
+ fn.restype = _ctypes.c_char_p # otherwise return is an int
538
+ p_name = fn(_cudaError_t(error))
539
+ name = _ctypes.string_at(p_name)
540
+ return name.decode('utf-8', errors='replace')
541
+
542
+
543
+ def cuGetErrorString(error: int) -> str:
544
+ """Get the description string for an error code.
545
+
546
+ Returns: str
547
+ The description string for an error code. If the error code is not recognized, "unrecognized
548
+ error code" is returned.
549
+
550
+ Raises:
551
+ cudaError_InitializationError:
552
+ If cannot found the CUDA Runtime library.
553
+ """
554
+ fn = __cudaGetFunctionPointer('cudaGetErrorString')
555
+
556
+ fn.restype = _ctypes.c_char_p # otherwise return is an int
557
+ p_name = fn(_cudaError_t(error))
558
+ name = _ctypes.string_at(p_name)
559
+ return name.decode('utf-8', errors='replace')
560
+
561
+
562
+ def cudaGetLastError() -> int:
563
+ """Get the last error from a runtime call.
564
+
565
+ Returns: int
566
+ The last error that has been produced by any of the runtime calls in the same instance of
567
+ the CUDA Runtime library in the host thread and resets it to :data:`cudaSuccess`.
568
+
569
+ Raises:
570
+ cudaError_InitializationError:
571
+ If cannot found the CUDA Runtime library.
572
+ cudaError_InsufficientDriver:
573
+ If the installed NVIDIA CUDA driver is older than the CUDA Runtime library.
574
+ cudaError_NoDevice:
575
+ If no CUDA-capable devices were detected by the installed CUDA driver.
576
+ """
577
+ fn = __cudaGetFunctionPointer('cudaGetLastError')
578
+ return fn()
579
+
580
+
581
+ def cudaPeekAtLastError() -> int:
582
+ """Get the last error from a runtime call.
583
+
584
+ Returns: int
585
+ The last error that has been produced by any of the runtime calls in the same instance of
586
+ the CUDA Runtime library in the host thread. This call does not reset the error to
587
+ :data:`cudaSuccess` like :func:`cudaGetLastError`.
588
+
589
+ Raises:
590
+ cudaError_InitializationError:
591
+ If cannot found the CUDA Runtime library.
592
+ cudaError_InsufficientDriver:
593
+ If the installed NVIDIA CUDA driver is older than the CUDA Runtime library.
594
+ cudaError_NoDevice:
595
+ If no CUDA-capable devices were detected by the installed CUDA driver.
596
+ """
597
+ fn = __cudaGetFunctionPointer('cudaPeekAtLastError')
598
+ return fn()
599
+
600
+
601
+ def cudaDriverGetVersion() -> str:
602
+ """Get the latest CUDA version supported by driver.
603
+
604
+ Returns: str
605
+ The latest version of CUDA supported by the driver of the form :data:`'<major>.<minor>'`.
606
+
607
+ Raises:
608
+ cudaError_InitializationError:
609
+ If cannot found the CUDA Runtime library.
610
+ cudaError_InsufficientDriver:
611
+ If the installed NVIDIA CUDA driver is older than the CUDA Runtime library.
612
+ cudaError_NoDevice:
613
+ If no CUDA-capable devices were detected by the installed CUDA driver.
614
+ """
615
+ fn = __cudaGetFunctionPointer('cudaDriverGetVersion')
616
+
617
+ driver_version = _ctypes.c_int(0)
618
+ ret = fn(_ctypes.byref(driver_version))
619
+ _cudaCheckReturn(ret)
620
+ major = driver_version.value // 1000
621
+ minor = (driver_version.value % 1000) // 10
622
+ return f'{major}.{minor}'
623
+
624
+
625
+ def cudaRuntimeGetVersion() -> str:
626
+ """Get the CUDA Runtime version.
627
+
628
+ Returns: str
629
+ The version number of the current CUDA Runtime instance of the form :data:`'<major>.<minor>'`.
630
+
631
+ Raises:
632
+ cudaError_InitializationError:
633
+ If cannot found the CUDA Runtime library.
634
+ cudaError_InsufficientDriver:
635
+ If the installed NVIDIA CUDA driver is older than the CUDA Runtime library.
636
+ cudaError_NoDevice:
637
+ If no CUDA-capable devices were detected by the installed CUDA driver.
638
+ """
639
+ fn = __cudaGetFunctionPointer('cudaRuntimeGetVersion')
640
+
641
+ runtime_version = _ctypes.c_int(0)
642
+ ret = fn(_ctypes.byref(runtime_version))
643
+ _cudaCheckReturn(ret)
644
+ major = runtime_version.value // 1000
645
+ minor = (runtime_version.value % 1000) // 10
646
+ return f'{major}.{minor}'
647
+
648
+
649
+ def cudaGetDeviceCount() -> int:
650
+ """Get the number of compute-capable devices.
651
+
652
+ Returns: int
653
+ The number of devices with compute capability greater or equal to 2.0 that are available for
654
+ execution.
655
+
656
+ Raises:
657
+ cudaError_InitializationError:
658
+ If cannot found the CUDA Runtime library.
659
+ cudaError_InsufficientDriver:
660
+ If the installed NVIDIA CUDA driver is older than the CUDA Runtime library.
661
+ cudaError_NoDevice:
662
+ If no CUDA-capable devices were detected by the installed CUDA driver.
663
+ """
664
+ fn = __cudaGetFunctionPointer('cudaGetDeviceCount')
665
+
666
+ count = _ctypes.c_int(0)
667
+ ret = fn(_ctypes.byref(count))
668
+ _cudaCheckReturn(ret)
669
+ return count.value
670
+
671
+
672
+ def cudaDeviceGetByPCIBusId(pciBusId: str) -> int:
673
+ """Get a handle to a compute device.
674
+
675
+ Args:
676
+ pciBusId (str):
677
+ String in one of the following forms: ``[domain]:[bus]:[device].[function]``,
678
+ ``[domain]:[bus]:[device]``, ``[bus]:[device].[function]`` where ``domain``, ``bus``,
679
+ ``device``, and ``function`` are all hexadecimal values.
680
+
681
+ Returns: int
682
+ A device ordinal given a PCI bus ID string.
683
+
684
+ Raises:
685
+ cudaError_InitializationError:
686
+ If cannot found the CUDA Runtime library.
687
+ cudaError_InsufficientDriver:
688
+ If the installed NVIDIA CUDA driver is older than the CUDA Runtime library.
689
+ cudaError_NoDevice:
690
+ If no CUDA-capable devices were detected by the installed CUDA driver.
691
+ cudaError_InvalidValue:
692
+ If the value of :data:`pciBusId` is not a valid PCI bus identifier.
693
+ cudaError_InvalidDevice:
694
+ If the device ordinal supplied by the user does not correspond to a valid CUDA device.
695
+ """
696
+ fn = __cudaGetFunctionPointer('cudaDeviceGetByPCIBusId')
697
+
698
+ device = _ctypes.c_int(0)
699
+ ret = fn(_ctypes.byref(device), _ctypes.c_char_p(pciBusId.encode('utf-8')))
700
+ _cudaCheckReturn(ret)
701
+ return device.value
702
+
703
+
704
+ def cudaDeviceGetPCIBusId(device: int) -> str:
705
+ """Get a PCI Bus Id string for the device.
706
+
707
+ Returns: str
708
+ An ASCII string identifying the device.
709
+
710
+ Raises:
711
+ cudaError_InitializationError:
712
+ If cannot found the CUDA Runtime library.
713
+ cudaError_InsufficientDriver:
714
+ If the installed NVIDIA CUDA driver is older than the CUDA Runtime library.
715
+ cudaError_NoDevice:
716
+ If no CUDA-capable devices were detected by the installed CUDA driver.
717
+ cudaError_InvalidValue:
718
+ If the value of :data:`device` is not a valid device ordinal.
719
+ cudaError_InvalidDevice:
720
+ If the device ordinal supplied by the user does not correspond to a valid CUDA device.
721
+ """
722
+ fn = __cudaGetFunctionPointer('cudaDeviceGetPCIBusId')
723
+
724
+ pciBusId = _ctypes.create_string_buffer(256)
725
+ ret = fn(pciBusId, _ctypes.c_int(256), _ctypes.c_int(device))
726
+ _cudaCheckReturn(ret)
727
+ return pciBusId.value.decode('utf-8', errors='replace')
728
+
729
+
730
+ def is_available() -> bool:
731
+ """Test whether there are any CUDA visible devices."""
732
+ try:
733
+ return cudaGetDeviceCount() > 0
734
+ except cudaError:
735
+ return False
.venv/lib/python3.10/site-packages/nvitop/api/libnvml.py ADDED
@@ -0,0 +1,1020 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is part of nvitop, the interactive NVIDIA-GPU process viewer.
2
+ #
3
+ # Copyright 2021-2025 Xuehai Pan. All Rights Reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ # ==============================================================================
17
+ """Utilities for the NVML Python bindings (`nvidia-ml-py <https://pypi.org/project/nvidia-ml-py>`_)."""
18
+
19
+ # pylint: disable=too-many-lines,invalid-name
20
+
21
+ from __future__ import annotations
22
+
23
+ import atexit as _atexit
24
+ import ctypes as _ctypes
25
+ import inspect as _inspect
26
+ import logging as _logging
27
+ import os as _os
28
+ import re as _re
29
+ import sys as _sys
30
+ import threading as _threading
31
+ import time as _time
32
+ from types import FunctionType as _FunctionType
33
+ from types import ModuleType as _ModuleType
34
+ from typing import TYPE_CHECKING as _TYPE_CHECKING
35
+ from typing import Any as _Any
36
+ from typing import ClassVar as _ClassVar
37
+
38
+ # Python Bindings for the NVIDIA Management Library (NVML)
39
+ # https://pypi.org/project/nvidia-ml-py
40
+ import pynvml as _pynvml
41
+ from pynvml import * # noqa: F403 # pylint: disable=wildcard-import,unused-wildcard-import
42
+ from pynvml import nvmlDeviceGetPciInfo # appease mypy # noqa: F401 # pylint: disable=unused-import
43
+
44
+ from nvitop.api.utils import NA, UINT_MAX, ULONGLONG_MAX, NaType
45
+ from nvitop.api.utils import colored as __colored
46
+
47
+
48
+ if _TYPE_CHECKING:
49
+ from collections.abc import Callable as _Callable
50
+ from typing_extensions import Self as _Self # Python 3.11+
51
+ from typing_extensions import TypeAlias as _TypeAlias # Python 3.10+
52
+
53
+
54
+ __all__ = [ # will be updated in below
55
+ 'NA',
56
+ 'UINT_MAX',
57
+ 'ULONGLONG_MAX',
58
+ 'NVMLError',
59
+ 'nvmlCheckReturn',
60
+ 'nvmlInit',
61
+ 'nvmlInitWithFlags',
62
+ 'nvmlQuery',
63
+ 'nvmlQueryFieldValues',
64
+ 'nvmlShutdown',
65
+ ]
66
+
67
+
68
+ if not callable(getattr(_pynvml, 'nvmlInitWithFlags', None)):
69
+ raise ImportError( # noqa: TRY004
70
+ 'Your installed package `nvidia-ml-py` is corrupted. Please reinstall package '
71
+ '`nvidia-ml-py` via `pip3 install --force-reinstall nvidia-ml-py nvitop`.',
72
+ )
73
+
74
+
75
+ # Members from `pynvml` ############################################################################
76
+
77
+ NVMLError: type[_pynvml.NVMLError] = _pynvml.NVMLError
78
+ NVMLError.__doc__ = """Base exception class for NVML query errors."""
79
+ NVMLError.__new__.__doc__ = """Map value to a proper subclass of :class:`NVMLError`."""
80
+ nvmlExceptionClass: _Callable[[int], type[_pynvml.NVMLError]] = _pynvml.nvmlExceptionClass
81
+ nvmlExceptionClass.__doc__ = """Map value to a proper subclass of :class:`NVMLError`."""
82
+
83
+ # Load members from module `pynvml` and register them in `__all__` and globals.
84
+ _vars_pynvml = vars(_pynvml)
85
+ _name = _attr = None
86
+ _errcode_to_name = {}
87
+ _const_names = []
88
+ _errcode_to_string = NVMLError._errcode_to_string # pylint: disable=protected-access
89
+
90
+ # 1. Put error classes in `__all__` first
91
+ for _name, _attr in _vars_pynvml.items():
92
+ if _name in {'nvmlInit', 'nvmlInitWithFlags', 'nvmlShutdown'}:
93
+ continue
94
+ if _name.startswith(('NVML_ERROR_', 'NVMLError_')):
95
+ __all__.append(_name) # noqa: PYI056
96
+ if _name.startswith('NVML_ERROR_'):
97
+ _errcode_to_name[_attr] = _name
98
+ _const_names.append(_name)
99
+
100
+ # 2. Then the remaining members
101
+ for _name, _attr in _vars_pynvml.items():
102
+ if _name in {'nvmlInit', 'nvmlInitWithFlags', 'nvmlShutdown'}:
103
+ continue
104
+ if (_name.startswith('NVML_') and not _name.startswith('NVML_ERROR_')) or (
105
+ _name.startswith('nvml') and isinstance(_attr, _FunctionType)
106
+ ):
107
+ __all__.append(_name) # noqa: PYI056
108
+ if _name.startswith('NVML_'):
109
+ _const_names.append(_name)
110
+
111
+ # 3. Add docstring to exception classes
112
+ _errcode = _reason = _subclass = None
113
+ for _errcode, _reason in _errcode_to_string.items():
114
+ _subclass = nvmlExceptionClass(_errcode)
115
+ _subclass.__doc__ = '{}. Code: :data:`{}` ({})'.format(
116
+ _reason.rstrip('.'),
117
+ _errcode_to_name[_errcode],
118
+ _errcode,
119
+ )
120
+
121
+ # 4. Add undocumented constants into module docstring
122
+ _data_docs = []
123
+ _sphinx_doc = None
124
+ for _name in _const_names:
125
+ _attr = _vars_pynvml[_name]
126
+ _sphinx_doc = f"""
127
+ .. data:: {_name}
128
+ :type: {_attr.__class__.__name__}
129
+ :value: {_attr!r}
130
+ """
131
+ if _name.startswith('NVML_ERROR_') and _attr in _errcode_to_string:
132
+ _reason = _errcode_to_string[_attr]
133
+ _sphinx_doc += """
134
+ {}. See also class :class:`NVMLError` and :class:`{}`.
135
+ """.format(_reason.rstrip('.'), nvmlExceptionClass(_attr).__name__) # fmt: skip
136
+ _data_docs.append(_sphinx_doc.strip())
137
+ __doc__ += """
138
+
139
+ ---------
140
+
141
+ Constants
142
+ ^^^^^^^^^
143
+
144
+ {}
145
+
146
+ ---------
147
+
148
+ Functions and Exceptions
149
+ ^^^^^^^^^^^^^^^^^^^^^^^^
150
+
151
+ .. function:: __enter__() -> libnvml
152
+
153
+ Entry of the context manager for ``with`` statement.
154
+
155
+ .. function:: __exit__(*args, **kwargs) -> None
156
+
157
+ Shutdown the NVML context in the context manager for ``with`` statement.
158
+
159
+ """.format('\n\n'.join(_data_docs)) # fmt: skip
160
+
161
+ del (
162
+ _name,
163
+ _attr,
164
+ _vars_pynvml,
165
+ _errcode,
166
+ _reason,
167
+ _subclass,
168
+ _errcode_to_name,
169
+ _errcode_to_string,
170
+ _const_names,
171
+ _data_docs,
172
+ _sphinx_doc,
173
+ )
174
+
175
+ # 5. Add explicit references to appease linters
176
+ # pylint: disable=no-member
177
+ if _TYPE_CHECKING:
178
+ # pylint: disable-next=missing-class-docstring,too-few-public-methods,function-redefined
179
+ class c_nvmlDevice_t(_ctypes.c_void_p):
180
+ pass
181
+
182
+ else:
183
+ c_nvmlDevice_t: _TypeAlias = _pynvml.c_nvmlDevice_t # type: ignore[no-redef] # noqa: PYI042
184
+
185
+ c_nvmlFieldValue_t: _TypeAlias = _pynvml.c_nvmlFieldValue_t # noqa: PYI042
186
+ NVML_SUCCESS: int = _pynvml.NVML_SUCCESS
187
+ NVML_ERROR_INSUFFICIENT_SIZE: int = _pynvml.NVML_ERROR_INSUFFICIENT_SIZE
188
+ NVMLError_FunctionNotFound: _TypeAlias = _pynvml.NVMLError_FunctionNotFound
189
+ NVMLError_GpuIsLost: _TypeAlias = _pynvml.NVMLError_GpuIsLost
190
+ NVMLError_InvalidArgument: _TypeAlias = _pynvml.NVMLError_InvalidArgument
191
+ NVMLError_LibraryNotFound: _TypeAlias = _pynvml.NVMLError_LibraryNotFound
192
+ NVMLError_NoPermission: _TypeAlias = _pynvml.NVMLError_NoPermission
193
+ NVMLError_NotFound: _TypeAlias = _pynvml.NVMLError_NotFound
194
+ NVMLError_NotSupported: _TypeAlias = _pynvml.NVMLError_NotSupported
195
+ NVMLError_Unknown: _TypeAlias = _pynvml.NVMLError_Unknown
196
+ NVML_CLOCK_GRAPHICS: int = _pynvml.NVML_CLOCK_GRAPHICS
197
+ NVML_CLOCK_SM: int = _pynvml.NVML_CLOCK_SM
198
+ NVML_CLOCK_MEM: int = _pynvml.NVML_CLOCK_MEM
199
+ NVML_CLOCK_VIDEO: int = _pynvml.NVML_CLOCK_VIDEO
200
+ NVML_TEMPERATURE_GPU: int = _pynvml.NVML_TEMPERATURE_GPU
201
+ NVML_DRIVER_WDDM: int = _pynvml.NVML_DRIVER_WDDM
202
+ NVML_DRIVER_WDM: int = _pynvml.NVML_DRIVER_WDM
203
+ NVML_MEMORY_ERROR_TYPE_UNCORRECTED: int = _pynvml.NVML_MEMORY_ERROR_TYPE_UNCORRECTED
204
+ NVML_VOLATILE_ECC: int = _pynvml.NVML_VOLATILE_ECC
205
+ NVML_COMPUTEMODE_DEFAULT: int = _pynvml.NVML_COMPUTEMODE_DEFAULT
206
+ NVML_COMPUTEMODE_EXCLUSIVE_THREAD: int = _pynvml.NVML_COMPUTEMODE_EXCLUSIVE_THREAD
207
+ NVML_COMPUTEMODE_PROHIBITED: int = _pynvml.NVML_COMPUTEMODE_PROHIBITED
208
+ NVML_COMPUTEMODE_EXCLUSIVE_PROCESS: int = _pynvml.NVML_COMPUTEMODE_EXCLUSIVE_PROCESS
209
+ NVML_PCIE_UTIL_TX_BYTES: int = _pynvml.NVML_PCIE_UTIL_TX_BYTES
210
+ NVML_PCIE_UTIL_RX_BYTES: int = _pynvml.NVML_PCIE_UTIL_RX_BYTES
211
+ NVML_NVLINK_MAX_LINKS: int = _pynvml.NVML_NVLINK_MAX_LINKS
212
+ NVML_FI_DEV_NVLINK_LINK_COUNT: int = _pynvml.NVML_FI_DEV_NVLINK_LINK_COUNT
213
+ NVML_FI_DEV_NVLINK_THROUGHPUT_DATA_TX: int = _pynvml.NVML_FI_DEV_NVLINK_THROUGHPUT_DATA_TX
214
+ NVML_FI_DEV_NVLINK_THROUGHPUT_DATA_RX: int = _pynvml.NVML_FI_DEV_NVLINK_THROUGHPUT_DATA_RX
215
+ NVML_FI_DEV_NVLINK_THROUGHPUT_RAW_TX: int = _pynvml.NVML_FI_DEV_NVLINK_THROUGHPUT_RAW_TX
216
+ NVML_FI_DEV_NVLINK_THROUGHPUT_RAW_RX: int = _pynvml.NVML_FI_DEV_NVLINK_THROUGHPUT_RAW_RX
217
+ NVML_VALUE_TYPE_DOUBLE: int = getattr(_pynvml, 'NVML_VALUE_TYPE_DOUBLE', 0)
218
+ NVML_VALUE_TYPE_UNSIGNED_INT: int = getattr(_pynvml, 'NVML_VALUE_TYPE_UNSIGNED_INT', 1)
219
+ NVML_VALUE_TYPE_UNSIGNED_LONG: int = getattr(_pynvml, 'NVML_VALUE_TYPE_UNSIGNED_LONG', 2)
220
+ NVML_VALUE_TYPE_UNSIGNED_LONG_LONG: int = getattr(_pynvml, 'NVML_VALUE_TYPE_UNSIGNED_LONG_LONG', 3)
221
+ NVML_VALUE_TYPE_SIGNED_LONG_LONG: int = getattr(_pynvml, 'NVML_VALUE_TYPE_SIGNED_LONG_LONG', 4)
222
+ NVML_VALUE_TYPE_SIGNED_INT: int = getattr(_pynvml, 'NVML_VALUE_TYPE_SIGNED_INT', 5)
223
+ # pylint: enable=no-member
224
+
225
+ # New members in `libnvml` #########################################################################
226
+
227
+ __flags: list[int] = []
228
+ __initialized: bool = False
229
+ __lock: _threading.Lock = _threading.Lock()
230
+
231
+ LOGGER: _logging.Logger = _logging.getLogger(__name__)
232
+ try:
233
+ LOGGER.setLevel(_os.getenv('LOGLEVEL', default='WARNING').upper())
234
+ except (ValueError, TypeError):
235
+ pass
236
+ if not LOGGER.hasHandlers() and LOGGER.isEnabledFor(_logging.DEBUG):
237
+ _formatter = _logging.Formatter(
238
+ '[%(levelname)s] %(asctime)s %(name)s::%(funcName)s: %(message)s',
239
+ )
240
+ _stream_handler = _logging.StreamHandler()
241
+ _stream_handler.setFormatter(_formatter)
242
+ _file_handler = _logging.FileHandler('nvitop.log')
243
+ _file_handler.setFormatter(_formatter)
244
+ LOGGER.addHandler(_stream_handler)
245
+ LOGGER.addHandler(_file_handler)
246
+ del _formatter, _stream_handler, _file_handler
247
+
248
+ UNKNOWN_FUNCTIONS: dict[str, tuple[_Callable | str, NVMLError_FunctionNotFound]] = {}
249
+ UNKNOWN_FUNCTIONS_CACHE_SIZE: int = 1024
250
+ VERSIONED_PATTERN: _re.Pattern = _re.compile(r'^(?P<name>\w+)(?P<suffix>_v(\d)+)$')
251
+
252
+
253
+ def _lazy_init() -> None:
254
+ """Lazily initialize the NVML context.
255
+
256
+ Raises:
257
+ NVMLError_LibraryNotFound:
258
+ If cannot find the NVML library, usually the NVIDIA driver is not installed.
259
+ NVMLError_DriverNotLoaded:
260
+ If NVIDIA driver is not loaded.
261
+ NVMLError_LibRmVersionMismatch:
262
+ If RM detects a driver/library version mismatch, usually after an upgrade for NVIDIA
263
+ driver without reloading the kernel module.
264
+ AttributeError:
265
+ If cannot find function :func:`pynvml.nvmlInitWithFlags`, usually the :mod:`pynvml` module
266
+ is overridden by other modules. Need to reinstall package ``nvidia-ml-py``.
267
+ """
268
+ if __initialized:
269
+ return
270
+
271
+ with __lock:
272
+ if __initialized:
273
+ return # type: ignore[unreachable]
274
+
275
+ nvmlInit()
276
+ _atexit.register(nvmlShutdown)
277
+
278
+
279
+ def nvmlInit() -> None: # pylint: disable=function-redefined
280
+ """Initialize the NVML context with default flag (0).
281
+
282
+ Raises:
283
+ NVMLError_LibraryNotFound:
284
+ If cannot find the NVML library, usually the NVIDIA driver is not installed.
285
+ NVMLError_DriverNotLoaded:
286
+ If NVIDIA driver is not loaded.
287
+ NVMLError_LibRmVersionMismatch:
288
+ If RM detects a driver/library version mismatch, usually after an upgrade for NVIDIA
289
+ driver without reloading the kernel module.
290
+ AttributeError:
291
+ If cannot find function :func:`pynvml.nvmlInitWithFlags`, usually the :mod:`pynvml` module
292
+ is overridden by other modules. Need to reinstall package ``nvidia-ml-py``.
293
+ """
294
+ nvmlInitWithFlags(0)
295
+
296
+
297
+ def nvmlInitWithFlags(flags: int) -> None: # pylint: disable=function-redefined
298
+ """Initialize the NVML context with the given flags.
299
+
300
+ Raises:
301
+ NVMLError_LibraryNotFound:
302
+ If cannot find the NVML library, usually the NVIDIA driver is not installed.
303
+ NVMLError_DriverNotLoaded:
304
+ If NVIDIA driver is not loaded.
305
+ NVMLError_LibRmVersionMismatch:
306
+ If RM detects a driver/library version mismatch, usually after an upgrade for NVIDIA
307
+ driver without reloading the kernel module.
308
+ AttributeError:
309
+ If cannot find function :func:`pynvml.nvmlInitWithFlags`, usually the :mod:`pynvml` module
310
+ is overridden by other modules. Need to reinstall package ``nvidia-ml-py``.
311
+ """
312
+ global __flags, __initialized # pylint: disable=global-statement,global-variable-not-assigned
313
+
314
+ with __lock:
315
+ if len(__flags) > 0 and flags == __flags[-1]:
316
+ __initialized = True
317
+ return
318
+
319
+ try:
320
+ _pynvml.nvmlInitWithFlags(flags)
321
+ except NVMLError_LibraryNotFound:
322
+ message = (
323
+ 'FATAL ERROR: NVIDIA Management Library (NVML) not found.\n'
324
+ 'HINT: The NVIDIA Management Library ships with the NVIDIA display driver (available at\n'
325
+ ' https://www.nvidia.com/Download/index.aspx), or can be downloaded as part of the\n'
326
+ ' NVIDIA CUDA Toolkit (available at https://developer.nvidia.com/cuda-downloads).\n'
327
+ ' The lists of OS platforms and NVIDIA-GPUs supported by the NVML library can be\n'
328
+ ' found in the NVML API Reference at https://docs.nvidia.com/deploy/nvml-api.'
329
+ )
330
+ for text, color, attrs in (
331
+ ('FATAL ERROR:', 'red', ('bold',)),
332
+ ('HINT:', 'yellow', ('bold',)),
333
+ ('https://www.nvidia.com/Download/index.aspx', None, ('underline',)),
334
+ ('https://developer.nvidia.com/cuda-downloads', None, ('underline',)),
335
+ ('https://docs.nvidia.com/deploy/nvml-api', None, ('underline',)),
336
+ ):
337
+ message = message.replace(text, __colored(text, color=color, attrs=attrs)) # type: ignore[arg-type]
338
+
339
+ LOGGER.critical(message)
340
+ raise
341
+ except AttributeError:
342
+ message = (
343
+ 'FATAL ERROR: The dependency package `nvidia-ml-py` is corrupted. You may have installed\n'
344
+ ' other packages overriding the module `pynvml`.\n'
345
+ 'Please reinstall `nvitop` with command:\n'
346
+ ' python3 -m pip install --force-reinstall nvitop'
347
+ )
348
+ for text, color, attrs in (
349
+ ('FATAL ERROR:', 'red', ('bold',)),
350
+ ('nvidia-ml-py', None, ('bold',)),
351
+ ('pynvml', None, ('bold',)),
352
+ ('nvitop', None, ('bold',)),
353
+ ):
354
+ message = message.replace(text, __colored(text, color=color, attrs=attrs), 1) # type: ignore[arg-type]
355
+
356
+ LOGGER.critical(message)
357
+ raise
358
+
359
+ with __lock:
360
+ __flags.append(flags)
361
+ __initialized = True
362
+
363
+
364
+ def nvmlShutdown() -> None: # pylint: disable=function-redefined
365
+ """Shutdown the NVML context.
366
+
367
+ Raises:
368
+ NVMLError_LibraryNotFound:
369
+ If cannot find the NVML library, usually the NVIDIA driver is not installed.
370
+ NVMLError_DriverNotLoaded:
371
+ If NVIDIA driver is not loaded.
372
+ NVMLError_LibRmVersionMismatch:
373
+ If RM detects a driver/library version mismatch, usually after an upgrade for NVIDIA
374
+ driver without reloading the kernel module.
375
+ NVMLError_Uninitialized:
376
+ If NVML was not first initialized with :func:`nvmlInit`.
377
+ """
378
+ global __flags, __initialized # pylint: disable=global-statement,global-variable-not-assigned
379
+
380
+ _pynvml.nvmlShutdown()
381
+ with __lock:
382
+ try:
383
+ __flags.pop()
384
+ except IndexError:
385
+ pass
386
+ __initialized = len(__flags) > 0
387
+
388
+
389
+ def nvmlQuery(
390
+ func: _Callable[..., _Any] | str,
391
+ /,
392
+ *args: _Any,
393
+ default: _Any = NA,
394
+ ignore_errors: bool = True,
395
+ ignore_function_not_found: bool = False,
396
+ **kwargs: _Any,
397
+ ) -> _Any:
398
+ """Call a function with the given arguments from NVML.
399
+
400
+ The NVML context will be automatically initialized.
401
+
402
+ Args:
403
+ func (Union[Callable[..., Any], str]):
404
+ The function to call. If it is given by string, lookup for the function first from
405
+ module :mod:`pynvml`.
406
+ default (Any):
407
+ The default value if the query fails.
408
+ ignore_errors (bool):
409
+ Whether to ignore errors and return the default value.
410
+ ignore_function_not_found (bool):
411
+ Whether to ignore function not found errors and return the default value. If set to
412
+ :data:`False`, an error message will be logged to the logger.
413
+ *args:
414
+ Positional arguments to pass to the query function.
415
+ **kwargs:
416
+ Keyword arguments to pass to the query function.
417
+
418
+ Raises:
419
+ NVMLError_LibraryNotFound:
420
+ If cannot find the NVML library, usually the NVIDIA driver is not installed.
421
+ NVMLError_DriverNotLoaded:
422
+ If NVIDIA driver is not loaded.
423
+ NVMLError_LibRmVersionMismatch:
424
+ If RM detects a driver/library version mismatch, usually after an upgrade for NVIDIA
425
+ driver without reloading the kernel module.
426
+ NVMLError_FunctionNotFound:
427
+ If the function is not found, usually the installed ``nvidia-ml-py`` is not compatible
428
+ with the installed NVIDIA driver.
429
+ NVMLError_NotSupported:
430
+ If the function is not supported by the driver or the device.
431
+ NVMLError_InvalidArgument:
432
+ If passed with an invalid argument.
433
+ """
434
+ global UNKNOWN_FUNCTIONS # pylint: disable=global-statement,global-variable-not-assigned
435
+
436
+ _lazy_init()
437
+
438
+ try:
439
+ if isinstance(func, str):
440
+ try:
441
+ func = getattr(__modself, func)
442
+ except AttributeError as e1:
443
+ raise NVMLError_FunctionNotFound from e1
444
+
445
+ try:
446
+ retval = func(*args, **kwargs) # type: ignore[operator]
447
+ except UnicodeDecodeError as e2:
448
+ raise NVMLError_Unknown from e2
449
+ except NVMLError_FunctionNotFound as e3:
450
+ if not ignore_function_not_found:
451
+ identifier = (
452
+ func
453
+ if isinstance(func, str)
454
+ else (_inspect.getsource(func) if func.__name__ == '<lambda>' else repr(func))
455
+ )
456
+ with __lock:
457
+ if (
458
+ identifier not in UNKNOWN_FUNCTIONS
459
+ and len(UNKNOWN_FUNCTIONS) < UNKNOWN_FUNCTIONS_CACHE_SIZE
460
+ ):
461
+ UNKNOWN_FUNCTIONS[identifier] = (func, e3)
462
+ LOGGER.exception(
463
+ (
464
+ 'ERROR: A FunctionNotFound error occurred while calling %s.\n'
465
+ 'Please verify whether the `nvidia-ml-py` package is '
466
+ 'compatible with your NVIDIA driver version.'
467
+ ),
468
+ f'nvmlQuery({func!r}, *args, **kwargs)',
469
+ )
470
+ if ignore_errors or ignore_function_not_found:
471
+ return default
472
+ raise
473
+ except NVMLError:
474
+ if ignore_errors:
475
+ return default
476
+ raise
477
+
478
+ if isinstance(retval, bytes):
479
+ retval = retval.decode('utf-8', errors='replace')
480
+ return retval
481
+
482
+
483
+ def nvmlQueryFieldValues(
484
+ handle: c_nvmlDevice_t,
485
+ field_ids: list[int | tuple[int, int]],
486
+ ) -> list[tuple[float | int | NaType, int]]:
487
+ """Query multiple field values from NVML.
488
+
489
+ Request values for a list of fields for a device. This API allows multiple fields to be queried
490
+ at once. If any of the underlying fieldIds are populated by the same driver call, the results
491
+ for those field IDs will be populated from a single call rather than making a driver call for
492
+ each fieldId.
493
+
494
+ Raises:
495
+ NVMLError_InvalidArgument:
496
+ If device or field_ids is invalid.
497
+ """
498
+ field_values = nvmlQuery('nvmlDeviceGetFieldValues', handle, field_ids)
499
+
500
+ if not nvmlCheckReturn(field_values):
501
+ timestamp = _time.time_ns() // 1000
502
+ return [(NA, timestamp) for _ in range(len(field_ids))]
503
+
504
+ values_with_timestamps: list[tuple[float | int | NaType, int]] = []
505
+ for field_value in field_values:
506
+ timestamp = field_value.timestamp
507
+ if field_value.nvmlReturn != NVML_SUCCESS:
508
+ value = NA
509
+ timestamp = _time.time_ns() // 1000
510
+ elif field_value.valueType == NVML_VALUE_TYPE_DOUBLE:
511
+ value = field_value.value.dVal
512
+ elif field_value.valueType == NVML_VALUE_TYPE_UNSIGNED_INT:
513
+ value = field_value.value.uiVal
514
+ elif field_value.valueType == NVML_VALUE_TYPE_UNSIGNED_LONG:
515
+ value = field_value.value.ulVal
516
+ elif field_value.valueType == NVML_VALUE_TYPE_UNSIGNED_LONG_LONG:
517
+ value = field_value.value.ullVal
518
+ elif field_value.valueType == NVML_VALUE_TYPE_SIGNED_LONG_LONG:
519
+ value = field_value.value.llVal
520
+ elif field_value.valueType == NVML_VALUE_TYPE_SIGNED_INT:
521
+ value = field_value.value.iVal
522
+ else:
523
+ value = NA
524
+ values_with_timestamps.append((value, timestamp))
525
+ return values_with_timestamps
526
+
527
+
528
+ def nvmlCheckReturn(retval: _Any, types: type | tuple[type, ...] | None = None, /) -> bool:
529
+ """Check whether the return value is not :const:`nvitop.NA` and is one of the given types."""
530
+ if types is None:
531
+ return retval != NA
532
+ return retval != NA and isinstance(retval, types)
533
+
534
+
535
+ # Patch layers for backward compatibility ##########################################################
536
+ _pynvml_installation_corrupted: bool = not callable(
537
+ getattr(_pynvml, '_nvmlGetFunctionPointer', None),
538
+ ) and isinstance(getattr(_pynvml, '_PrintableStructure', None), type)
539
+
540
+ # Patch function `nvmlDeviceGet{Compute,Graphics,MPSCompute}RunningProcesses`
541
+ if not _pynvml_installation_corrupted:
542
+ # pylint: disable-next=ungrouped-imports
543
+ from pynvml import _nvmlGetFunctionPointer, _PrintableStructure, nvmlStructToFriendlyObject
544
+
545
+ def _nvmlLookupFunctionPointer(symbol: str) -> _Any | None:
546
+ try:
547
+ ptr = _nvmlGetFunctionPointer(symbol)
548
+ except NVMLError_FunctionNotFound:
549
+ LOGGER.debug('Failed to found symbol `%s`.', symbol)
550
+ return None
551
+ LOGGER.debug('Found symbol `%s`.', symbol)
552
+ return ptr
553
+
554
+ # pylint: disable-next=missing-class-docstring,too-few-public-methods,function-redefined
555
+ class c_nvmlProcessInfo_v1_t(_PrintableStructure):
556
+ _fields_: _ClassVar[list[tuple[str, type]]] = [
557
+ # Process ID
558
+ ('pid', _ctypes.c_uint),
559
+ # Amount of used GPU memory in bytes.
560
+ # Under WDDM, NVML_VALUE_NOT_AVAILABLE is always reported because Windows KMD manages
561
+ # all the memory and not the NVIDIA driver.
562
+ ('usedGpuMemory', _ctypes.c_ulonglong),
563
+ ]
564
+ _fmt_: _ClassVar[dict[str, str]] = {
565
+ 'usedGpuMemory': '%d B',
566
+ }
567
+
568
+ # pylint: disable-next=missing-class-docstring,too-few-public-methods,function-redefined
569
+ class c_nvmlProcessInfo_v2_t(_PrintableStructure):
570
+ _fields_: _ClassVar[list[tuple[str, type]]] = [
571
+ # Process ID
572
+ ('pid', _ctypes.c_uint),
573
+ # Amount of used GPU memory in bytes.
574
+ # Under WDDM, NVML_VALUE_NOT_AVAILABLE is always reported because Windows KMD manages
575
+ # all the memory and not the NVIDIA driver.
576
+ ('usedGpuMemory', _ctypes.c_ulonglong),
577
+ # If MIG is enabled, stores a valid GPU instance ID. gpuInstanceId is set to 0xFFFFFFFF
578
+ # otherwise.
579
+ ('gpuInstanceId', _ctypes.c_uint),
580
+ # If MIG is enabled, stores a valid compute instance ID. computeInstanceId is set to
581
+ # 0xFFFFFFFF otherwise.
582
+ ('computeInstanceId', _ctypes.c_uint),
583
+ ]
584
+ _fmt_: _ClassVar[dict[str, str]] = {
585
+ 'usedGpuMemory': '%d B',
586
+ }
587
+
588
+ # pylint: disable-next=missing-class-docstring,too-few-public-methods,function-redefined
589
+ class c_nvmlProcessInfo_v3_t(_PrintableStructure):
590
+ _fields_: _ClassVar[list[tuple[str, type]]] = [
591
+ # Process ID
592
+ ('pid', _ctypes.c_uint),
593
+ # Amount of used GPU memory in bytes.
594
+ # Under WDDM, NVML_VALUE_NOT_AVAILABLE is always reported because Windows KMD manages
595
+ # all the memory and not the NVIDIA driver.
596
+ ('usedGpuMemory', _ctypes.c_ulonglong),
597
+ # If MIG is enabled, stores a valid GPU instance ID. gpuInstanceId is set to 0xFFFFFFFF
598
+ # otherwise.
599
+ ('gpuInstanceId', _ctypes.c_uint),
600
+ # If MIG is enabled, stores a valid compute instance ID. computeInstanceId is set to
601
+ # 0xFFFFFFFF otherwise.
602
+ ('computeInstanceId', _ctypes.c_uint),
603
+ # Amount of used GPU conf compute protected memory in bytes.
604
+ ('usedGpuCcProtectedMemory', _ctypes.c_ulonglong),
605
+ ]
606
+ _fmt_: _ClassVar[dict[str, str]] = {
607
+ 'usedGpuMemory': '%d B',
608
+ 'usedGpuCcProtectedMemory': '%d B',
609
+ }
610
+
611
+ __get_running_processes_version_suffix: str | None = None
612
+ c_nvmlProcessInfo_t = c_nvmlProcessInfo_v3_t
613
+
614
+ def __determine_get_running_processes_version_suffix() -> str:
615
+ global __get_running_processes_version_suffix, c_nvmlProcessInfo_t # pylint: disable=global-statement
616
+
617
+ if __get_running_processes_version_suffix is None:
618
+ __get_running_processes_version_suffix = '_v3'
619
+ if _nvmlLookupFunctionPointer('nvmlDeviceGetComputeRunningProcesses_v3') is not None:
620
+ if (
621
+ _nvmlLookupFunctionPointer('nvmlDeviceGetConfComputeMemSizeInfo') is not None
622
+ and _nvmlLookupFunctionPointer('nvmlDeviceGetRunningProcessDetailList') is None
623
+ ):
624
+ LOGGER.debug(
625
+ 'NVML get running process version 3 API with v3 type struct is available.',
626
+ )
627
+ else:
628
+ c_nvmlProcessInfo_t = c_nvmlProcessInfo_v2_t
629
+ LOGGER.debug(
630
+ 'NVML get running process version 3 API with v3 type struct is not '
631
+ 'available due to incompatible NVIDIA driver. Fallback to use get running '
632
+ 'process version 3 API with v2 type struct.',
633
+ )
634
+ else:
635
+ c_nvmlProcessInfo_t = c_nvmlProcessInfo_v2_t
636
+ __get_running_processes_version_suffix = '_v2'
637
+ LOGGER.debug(
638
+ 'NVML get running process version 3 API with v3 type struct is not available '
639
+ 'due to incompatible NVIDIA driver. Fallback to use get running process '
640
+ 'version 2 API with v2 type struct.',
641
+ )
642
+ if (
643
+ _nvmlLookupFunctionPointer('nvmlDeviceGetComputeRunningProcesses_v2')
644
+ is not None
645
+ ):
646
+ LOGGER.debug(
647
+ 'NVML get running process version 2 API with v2 type struct is available.',
648
+ )
649
+ else:
650
+ c_nvmlProcessInfo_t = c_nvmlProcessInfo_v1_t
651
+ __get_running_processes_version_suffix = ''
652
+ LOGGER.debug(
653
+ 'NVML get running process version 2 API with v2 type struct is not '
654
+ 'available due to incompatible NVIDIA driver. Fallback to use get '
655
+ 'running process version 1 API with v1 type struct.',
656
+ )
657
+
658
+ return __get_running_processes_version_suffix
659
+
660
+ def __nvml_device_get_running_processes(
661
+ func: str,
662
+ /,
663
+ handle: c_nvmlDevice_t,
664
+ ) -> list[c_nvmlProcessInfo_t]:
665
+ """Helper function for :func:`nvmlDeviceGet{Compute,Graphics,MPSCompute}RunningProcesses`.
666
+
667
+ Modified from function :func:`pynvml.nvmlDeviceGetComputeRunningProcesses` in package
668
+ `nvidia-ml-py <https://pypi.org/project/nvidia-ml-py>`_.
669
+ """
670
+ version_suffix = __determine_get_running_processes_version_suffix()
671
+
672
+ # First call to get the size
673
+ c_count = _ctypes.c_uint(0)
674
+ fn = _nvmlGetFunctionPointer(f'{func}{version_suffix}')
675
+ ret = fn(handle, _ctypes.byref(c_count), None)
676
+
677
+ if ret == NVML_SUCCESS:
678
+ # Special case, no running processes
679
+ return []
680
+ if ret == NVML_ERROR_INSUFFICIENT_SIZE:
681
+ # Typical case
682
+ # Oversize the array in case more processes are created
683
+ c_count.value = c_count.value * 2 + 5
684
+ process_array = c_nvmlProcessInfo_t * c_count.value # type: ignore[operator]
685
+ c_processes = process_array() # type: ignore[operator]
686
+
687
+ # Make the call again
688
+ ret = fn(handle, _ctypes.byref(c_count), c_processes)
689
+ if ret != NVML_SUCCESS:
690
+ raise NVMLError(ret)
691
+
692
+ processes = []
693
+ for i in range(c_count.value):
694
+ # Use an alternative struct for this object
695
+ obj = nvmlStructToFriendlyObject(c_processes[i])
696
+ if obj.usedGpuMemory == ULONGLONG_MAX:
697
+ # Special case for WDDM on Windows, see comment above
698
+ obj.usedGpuMemory = None
699
+ processes.append(obj)
700
+
701
+ return processes
702
+
703
+ # Error case
704
+ raise NVMLError(ret)
705
+
706
+ def nvmlDeviceGetComputeRunningProcesses( # pylint: disable=function-redefined
707
+ handle: c_nvmlDevice_t,
708
+ ) -> list[c_nvmlProcessInfo_t]:
709
+ """Get information about processes with a compute context on a device.
710
+
711
+ Note:
712
+ - In MIG mode, if device handle is provided, the API returns aggregate information, only
713
+ if the caller has appropriate privileges. Per-instance information can be queried by
714
+ using specific MIG device handles.
715
+
716
+ Raises:
717
+ NVMLError_Uninitialized:
718
+ If NVML was not first initialized with :func:`nvmlInit`.
719
+ NVMLError_NoPermission:
720
+ If the user doesn't have permission to perform this operation.
721
+ NVMLError_InvalidArgument:
722
+ If device is invalid.
723
+ NVMLError_GpuIsLost:
724
+ If the target GPU has fallen off the bus or is otherwise inaccessible.
725
+ NVMLError_Unknown:
726
+ On any unexpected error.
727
+ """
728
+ return __nvml_device_get_running_processes('nvmlDeviceGetComputeRunningProcesses', handle)
729
+
730
+ def nvmlDeviceGetGraphicsRunningProcesses( # pylint: disable=function-redefined
731
+ handle: c_nvmlDevice_t,
732
+ ) -> list[c_nvmlProcessInfo_t]:
733
+ """Get information about processes with a graphics context on a device.
734
+
735
+ Note:
736
+ - In MIG mode, if device handle is provided, the API returns aggregate information, only
737
+ if the caller has appropriate privileges. Per-instance information can be queried by
738
+ using specific MIG device handles.
739
+
740
+ Raises:
741
+ NVMLError_Uninitialized:
742
+ If NVML was not first initialized with :func:`nvmlInit`.
743
+ NVMLError_NoPermission:
744
+ If the user doesn't have permission to perform this operation.
745
+ NVMLError_InvalidArgument:
746
+ If device is invalid.
747
+ NVMLError_GpuIsLost:
748
+ If the target GPU has fallen off the bus or is otherwise inaccessible.
749
+ NVMLError_Unknown:
750
+ On any unexpected error.
751
+ """
752
+ return __nvml_device_get_running_processes('nvmlDeviceGetGraphicsRunningProcesses', handle)
753
+
754
+ def nvmlDeviceGetMPSComputeRunningProcesses( # pylint: disable=function-redefined
755
+ handle: c_nvmlDevice_t,
756
+ ) -> list[c_nvmlProcessInfo_t]:
757
+ """Get information about processes with a MPS compute context on a device.
758
+
759
+ Note:
760
+ - In MIG mode, if device handle is provided, the API returns aggregate information, only
761
+ if the caller has appropriate privileges. Per-instance information can be queried by
762
+ using specific MIG device handles.
763
+
764
+ Raises:
765
+ NVMLError_Uninitialized:
766
+ If NVML was not first initialized with :func:`nvmlInit`.
767
+ NVMLError_NoPermission:
768
+ If the user doesn't have permission to perform this operation.
769
+ NVMLError_InvalidArgument:
770
+ If device is invalid.
771
+ NVMLError_GpuIsLost:
772
+ If the target GPU has fallen off the bus or is otherwise inaccessible.
773
+ NVMLError_Unknown:
774
+ On any unexpected error.
775
+ """
776
+ return __nvml_device_get_running_processes(
777
+ 'nvmlDeviceGetMPSComputeRunningProcesses',
778
+ handle,
779
+ )
780
+
781
+ else:
782
+ LOGGER.warning(
783
+ 'Your installed package `nvidia-ml-py` is corrupted. '
784
+ 'Skip patch functions `nvmlDeviceGet{Compute,Graphics,MPSCompute}RunningProcesses`. '
785
+ 'You may get incorrect or incomplete results. Please consider reinstall package '
786
+ '`nvidia-ml-py` via `pip3 install --force-reinstall nvidia-ml-py nvitop`.',
787
+ )
788
+
789
+ # Patch function `nvmlDeviceGetMemoryInfo`
790
+ if not _pynvml_installation_corrupted:
791
+ # pylint: disable-next=missing-class-docstring,too-few-public-methods,function-redefined
792
+ class c_nvmlMemory_v1_t(_PrintableStructure):
793
+ _fields_: _ClassVar[list[tuple[str, type]]] = [
794
+ # Total physical device memory (in bytes).
795
+ ('total', _ctypes.c_ulonglong),
796
+ # Unallocated device memory (in bytes).
797
+ ('free', _ctypes.c_ulonglong),
798
+ # Allocated device memory (in bytes).
799
+ # Note that the driver/GPU always sets aside a small amount of memory for bookkeeping.
800
+ ('used', _ctypes.c_ulonglong),
801
+ ]
802
+ _fmt_: _ClassVar[dict[str, str]] = {'<default>': '%d B'}
803
+
804
+ # pylint: disable-next=missing-class-docstring,too-few-public-methods,function-redefined
805
+ class c_nvmlMemory_v2_t(_PrintableStructure):
806
+ _fields_: _ClassVar[list[tuple[str, type]]] = [
807
+ # Structure format version (must be 2).
808
+ ('version', _ctypes.c_uint),
809
+ # Total physical device memory (in bytes).
810
+ ('total', _ctypes.c_ulonglong),
811
+ # Device memory (in bytes) reserved for system use (driver or firmware).
812
+ ('reserved', _ctypes.c_ulonglong),
813
+ # Unallocated device memory (in bytes).
814
+ ('free', _ctypes.c_ulonglong),
815
+ # Allocated device memory (in bytes).
816
+ # Note that the driver/GPU always sets aside a small amount of memory for bookkeeping.
817
+ ('used', _ctypes.c_ulonglong),
818
+ ]
819
+ _fmt_: _ClassVar[dict[str, str]] = {'<default>': '%d B'}
820
+
821
+ nvmlMemory_v2 = getattr(_pynvml, 'nvmlMemory_v2', _ctypes.sizeof(c_nvmlMemory_v2_t) | (2 << 24))
822
+ __get_memory_info_version_suffix: str | None = None
823
+ c_nvmlMemory_t = c_nvmlMemory_v2_t
824
+
825
+ def __determine_get_memory_info_version_suffix() -> str:
826
+ global __get_memory_info_version_suffix, c_nvmlMemory_t # pylint: disable=global-statement
827
+
828
+ if __get_memory_info_version_suffix is None:
829
+ __get_memory_info_version_suffix = '_v2'
830
+ if _nvmlLookupFunctionPointer('nvmlDeviceGetMemoryInfo_v2') is not None:
831
+ LOGGER.debug('NVML get memory info version 2 is available.')
832
+ else:
833
+ c_nvmlMemory_t = c_nvmlMemory_v1_t
834
+ __get_memory_info_version_suffix = ''
835
+ LOGGER.debug(
836
+ 'NVML get memory info version 2 API is not available due to incompatible '
837
+ 'NVIDIA driver. Fallback to use NVML get memory info version 1 API.',
838
+ )
839
+
840
+ return __get_memory_info_version_suffix
841
+
842
+ def nvmlDeviceGetMemoryInfo( # pylint: disable=function-redefined
843
+ handle: c_nvmlDevice_t,
844
+ ) -> c_nvmlMemory_t:
845
+ """Retrieve the amount of used, free, reserved and total memory available on the device, in bytes.
846
+
847
+ Note:
848
+ - The version 2 API adds additional memory information. The reserved amount is supported
849
+ on version 2 only.
850
+ - In MIG mode, if device handle is provided, the API returns aggregate information, only
851
+ if the caller has appropriate privileges. Per-instance information can be queried by
852
+ using specific MIG device handles.
853
+
854
+ Raises:
855
+ NVMLError_Uninitialized:
856
+ If NVML was not first initialized with :func:`nvmlInit`.
857
+ NVMLError_NoPermission:
858
+ If the user doesn't have permission to perform this operation.
859
+ NVMLError_InvalidArgument:
860
+ If device is invalid.
861
+ NVMLError_GpuIsLost:
862
+ If the target GPU has fallen off the bus or is otherwise inaccessible.
863
+ NVMLError_Unknown:
864
+ On any unexpected error.
865
+ """
866
+ version_suffix = __determine_get_memory_info_version_suffix()
867
+ if version_suffix == '_v2':
868
+ c_memory = c_nvmlMemory_v2_t()
869
+ c_memory.version = nvmlMemory_v2 # pylint: disable=attribute-defined-outside-init
870
+ elif version_suffix in {'_v1', ''}:
871
+ c_memory = c_nvmlMemory_v1_t()
872
+ version_suffix = ''
873
+ else:
874
+ raise ValueError(
875
+ f'Unknown version suffix {version_suffix!r} for '
876
+ 'function `nvmlDeviceGetMemoryInfo`.',
877
+ )
878
+
879
+ fn = _nvmlGetFunctionPointer(f'nvmlDeviceGetMemoryInfo{version_suffix}')
880
+ ret = fn(handle, _ctypes.byref(c_memory))
881
+ if ret != NVML_SUCCESS:
882
+ raise NVMLError(ret)
883
+ return c_memory
884
+
885
+ else:
886
+ LOGGER.warning(
887
+ 'Your installed package `nvidia-ml-py` is corrupted. '
888
+ 'Skip patch functions `nvmlDeviceGetMemoryInfo`. '
889
+ 'You may get incorrect or incomplete results. Please consider reinstall package '
890
+ '`nvidia-ml-py` via `pip3 install --force-reinstall nvidia-ml-py nvitop`.',
891
+ )
892
+
893
+ # Patch function `nvmlDeviceGetTemperature`
894
+ if not _pynvml_installation_corrupted:
895
+ # pylint: disable-next=missing-class-docstring,too-few-public-methods,function-redefined
896
+ class c_nvmlTemperature_v1_t(_PrintableStructure):
897
+ _fields_: _ClassVar[list[tuple[str, type]]] = [
898
+ # Structure format version (must be 1).
899
+ ('version', _ctypes.c_uint),
900
+ # Sensor type.
901
+ ('sensorType', _ctypes.c_uint),
902
+ # Temperature in degrees Celsius.
903
+ ('temperature', _ctypes.c_int),
904
+ ]
905
+
906
+ nvmlTemperature_v1: int = getattr(
907
+ _pynvml,
908
+ 'nvmlTemperature_v1',
909
+ _ctypes.sizeof(c_nvmlTemperature_v1_t) | (1 << 24),
910
+ )
911
+ __get_temperature_version_suffix: str | None = None
912
+
913
+ def __determine_get_temperature_version_suffix() -> str:
914
+ """Determine the version suffix for the NVML temperature functions."""
915
+ global __get_temperature_version_suffix # pylint: disable=global-statement
916
+
917
+ if __get_temperature_version_suffix is None:
918
+ __get_temperature_version_suffix = 'V'
919
+ if _nvmlLookupFunctionPointer('nvmlDeviceGetTemperatureV') is not None:
920
+ LOGGER.debug('NVML get temperature version 1 API is available.')
921
+ else:
922
+ __get_temperature_version_suffix = ''
923
+ LOGGER.debug(
924
+ 'NVML get temperature version 1 API is not available due to incompatible '
925
+ 'NVIDIA driver. Fallback to use NVML get temperature API without version.',
926
+ )
927
+
928
+ return __get_temperature_version_suffix
929
+
930
+ def nvmlDeviceGetTemperature( # pylint: disable=function-redefined
931
+ handle: c_nvmlDevice_t,
932
+ sensor: int,
933
+ ) -> int:
934
+ """Retrieve the current temperature readings (in degrees C) for the given device.
935
+
936
+ Raises:
937
+ NVMLError_Uninitialized:
938
+ If NVML was not first initialized with :func:`nvmlInit`.
939
+ NVMLError_InvalidArgument:
940
+ If device is invalid, sensorType is invalid or temp is NULL.
941
+ NVMLError_NotSupported:
942
+ If the device does not have the specified sensor.
943
+ NVMLError_GpuIsLost:
944
+ If the target GPU has fallen off the bus or is otherwise inaccessible.
945
+ NVMLError_Unknown:
946
+ On any unexpected error.
947
+ """
948
+ version_suffix = __determine_get_temperature_version_suffix()
949
+ if version_suffix == 'V':
950
+ c_temp_v1 = c_nvmlTemperature_v1_t()
951
+ # pylint: disable-next=attribute-defined-outside-init
952
+ c_temp_v1.version = nvmlTemperature_v1
953
+ # pylint: disable-next=attribute-defined-outside-init
954
+ c_temp_v1.sensorType = _ctypes.c_uint(sensor)
955
+ fn = _nvmlGetFunctionPointer('nvmlDeviceGetTemperatureV')
956
+ ret = fn(handle, _ctypes.byref(c_temp_v1))
957
+ if ret != NVML_SUCCESS:
958
+ raise NVMLError(ret)
959
+ return int(c_temp_v1.temperature)
960
+
961
+ if version_suffix == '':
962
+ c_temp = _ctypes.c_uint(0)
963
+ fn = _nvmlGetFunctionPointer('nvmlDeviceGetTemperature')
964
+ ret = fn(handle, _ctypes.c_uint(sensor), _ctypes.byref(c_temp))
965
+ if ret != NVML_SUCCESS:
966
+ raise NVMLError(ret)
967
+ return c_temp.value
968
+
969
+ raise ValueError(
970
+ f'Unknown version suffix {version_suffix!r} for function `nvmlDeviceGetTemperature`.',
971
+ )
972
+
973
+ else:
974
+ LOGGER.warning(
975
+ 'Your installed package `nvidia-ml-py` is corrupted. '
976
+ 'Skip patch functions `nvmlDeviceGetTemperature`. '
977
+ 'You may get incorrect or incomplete results. Please consider reinstall package '
978
+ '`nvidia-ml-py` via `pip3 install --force-reinstall nvidia-ml-py nvitop`.',
979
+ )
980
+
981
+
982
+ # Add support for lookup fallback and context manager ##############################################
983
+ class _CustomModule(_ModuleType):
984
+ """Modified module type to support lookup fallback and context manager.
985
+
986
+ Automatic lookup fallback:
987
+
988
+ >>> libnvml.c_nvmlGpuInstance_t # fallback to pynvml.c_nvmlGpuInstance_t
989
+ <class 'pynvml.LP_struct_c_nvmlGpuInstance_t'>
990
+
991
+ Context manager:
992
+
993
+ >>> with libnvml:
994
+ ... handle = libnvml.nvmlDeviceGetHandleByIndex(0)
995
+ ... # The NVML context has been shutdown
996
+ """
997
+
998
+ def __getattribute__(self, name: str) -> _Any | _Callable[..., _Any]:
999
+ """Get a member from the current module. Fallback to the original package if missing."""
1000
+ try:
1001
+ return super().__getattribute__(name)
1002
+ except AttributeError:
1003
+ return getattr(_pynvml, name)
1004
+
1005
+ def __enter__(self) -> _Self:
1006
+ """Entry of the context manager for ``with`` statement."""
1007
+ _lazy_init()
1008
+ return self
1009
+
1010
+ def __exit__(self, *exc: object) -> None:
1011
+ """Shutdown the NVML context in the context manager for ``with`` statement."""
1012
+ try:
1013
+ nvmlShutdown()
1014
+ except NVMLError:
1015
+ pass
1016
+
1017
+
1018
+ # Replace entry in sys.modules for this module with an instance of _CustomModule
1019
+ __modself = _sys.modules[__name__]
1020
+ __modself.__class__ = _CustomModule
.venv/lib/python3.10/site-packages/nvitop/api/process.py ADDED
@@ -0,0 +1,1056 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is part of nvitop, the interactive NVIDIA-GPU process viewer.
2
+ #
3
+ # Copyright 2021-2025 Xuehai Pan. All Rights Reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ # ==============================================================================
17
+ """The live classes for process running on the host and the GPU devices."""
18
+
19
+ # pylint: disable=too-many-lines
20
+
21
+ from __future__ import annotations
22
+
23
+ import contextlib
24
+ import datetime
25
+ import functools
26
+ import os
27
+ import threading
28
+ from abc import ABC
29
+ from types import FunctionType
30
+ from typing import TYPE_CHECKING, Any
31
+ from weakref import WeakValueDictionary
32
+
33
+ from nvitop.api import host, libnvml
34
+ from nvitop.api.utils import (
35
+ NA,
36
+ UINT_MAX,
37
+ NaType,
38
+ Snapshot,
39
+ bytes2human,
40
+ memoize_when_activated,
41
+ timedelta2human,
42
+ )
43
+
44
+
45
+ if TYPE_CHECKING:
46
+ from collections.abc import Callable, Generator, Iterable
47
+ from typing_extensions import Self # Python 3.11+
48
+
49
+ from nvitop.api.device import Device
50
+
51
+
52
+ __all__ = ['GpuProcess', 'HostProcess', 'command_join']
53
+
54
+
55
+ if host.POSIX:
56
+
57
+ def add_quotes(s: str) -> str:
58
+ """Return a shell-escaped version of the string."""
59
+ if s == '':
60
+ return '""'
61
+ if '$' not in s and '\\' not in s and '\n' not in s:
62
+ if ' ' not in s:
63
+ return s
64
+ if '"' not in s:
65
+ return f'"{s}"'
66
+ if "'" not in s and '\n' not in s:
67
+ return f"'{s}'"
68
+ return '"{}"'.format(
69
+ s.replace('\\', r'\\').replace('"', r'\"').replace('$', r'\$').replace('\n', r'\n'),
70
+ )
71
+
72
+ elif host.WINDOWS:
73
+
74
+ def add_quotes(s: str) -> str:
75
+ """Return a shell-escaped version of the string."""
76
+ if s == '':
77
+ return '""'
78
+ if '%' not in s and '^' not in s and '\n' not in s:
79
+ if ' ' not in s:
80
+ return s
81
+ if '"' not in s:
82
+ return f'"{s}"'
83
+ return '"{}"'.format(
84
+ s.replace('^', '^^').replace('"', '^"').replace('%', '^%').replace('\n', r'\n'),
85
+ )
86
+
87
+ else:
88
+
89
+ def add_quotes(s: str) -> str:
90
+ """Return a shell-escaped version of the string."""
91
+ return '"{}"'.format(s.replace('\n', r'\n'))
92
+
93
+
94
+ def command_join(cmdline: list[str]) -> str:
95
+ """Return a shell-escaped string from command line arguments."""
96
+ if len(cmdline) == 1 and not (
97
+ # May be modified by `setproctitle`
98
+ os.path.isfile(cmdline[0]) and os.path.isabs(cmdline[0])
99
+ ):
100
+ return cmdline[0]
101
+ return ' '.join(map(add_quotes, cmdline))
102
+
103
+
104
+ _RAISE = object()
105
+ _USE_FALLBACK_WHEN_RAISE = threading.local() # see also `GpuProcess.failsafe`
106
+
107
+
108
+ def auto_garbage_clean(
109
+ fallback: Any = _RAISE,
110
+ ) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
111
+ """Remove the object references in the instance cache if the method call fails (the process is gone).
112
+
113
+ The fallback value will be used with `:meth:`GpuProcess.failsafe`` context manager, otherwise
114
+ raises an exception when falls.
115
+ """
116
+
117
+ def wrapper(func: Callable[..., Any], /) -> Callable[..., Any]:
118
+ @functools.wraps(func)
119
+ def wrapped(self: GpuProcess, /, *args: Any, **kwargs: Any) -> Any:
120
+ try:
121
+ return func(self, *args, **kwargs)
122
+ except host.PsutilError as ex:
123
+ try:
124
+ with GpuProcess.INSTANCE_LOCK:
125
+ del GpuProcess.INSTANCES[self.pid, self.device]
126
+ except (KeyError, AttributeError):
127
+ pass
128
+ try:
129
+ with HostProcess.INSTANCE_LOCK:
130
+ del HostProcess.INSTANCES[self.pid]
131
+ except KeyError:
132
+ pass
133
+ # See also `GpuProcess.failsafe`
134
+ if fallback is _RAISE or not getattr(_USE_FALLBACK_WHEN_RAISE, 'value', False):
135
+ raise
136
+ if isinstance(fallback, tuple):
137
+ if isinstance(ex, host.AccessDenied) and fallback == ('No Such Process',):
138
+ return ['No Permissions']
139
+ return list(fallback)
140
+ return fallback
141
+
142
+ return wrapped
143
+
144
+ return wrapper
145
+
146
+
147
+ class HostProcess(host.Process, ABC):
148
+ """Represent an OS process with the given PID.
149
+
150
+ If PID is omitted current process PID (:func:`os.getpid`) is used. The instance will be cache
151
+ during the lifetime of the process.
152
+
153
+ Examples:
154
+ >>> HostProcess() # the current process
155
+ HostProcess(pid=12345, name='python3', status='running', started='00:55:43')
156
+
157
+ >>> p1 = HostProcess(12345)
158
+ >>> p2 = HostProcess(12345)
159
+ >>> p1 is p2 # the same instance
160
+ True
161
+
162
+ >>> import copy
163
+ >>> copy.deepcopy(p1) is p1 # the same instance
164
+ True
165
+
166
+ >>> p = HostProcess(pid=12345)
167
+ >>> p.cmdline()
168
+ ['python3', '-c', 'import IPython; IPython.terminal.ipapp.launch_new_instance()']
169
+ >>> p.command() # the result is in shell-escaped format
170
+ 'python3 -c "import IPython; IPython.terminal.ipapp.launch_new_instance()"'
171
+
172
+ >>> p.as_snapshot()
173
+ HostProcessSnapshot(
174
+ real=HostProcess(pid=12345, name='python3', status='running', started='00:55:43'),
175
+ cmdline=['python3', '-c', 'import IPython; IPython.terminal.ipapp.launch_new_instance()'],
176
+ command='python3 -c "import IPython; IPython.terminal.ipapp.launch_new_instance()"',
177
+ connections=[],
178
+ cpu_percent=0.3,
179
+ cpu_times=pcputimes(user=2.180019456, system=0.18424464, children_user=0.0, children_system=0.0),
180
+ create_time=1656608143.31,
181
+ cwd='/home/panxuehai',
182
+ environ={...},
183
+ ...
184
+ )
185
+ """
186
+
187
+ INSTANCE_LOCK: threading.RLock = threading.RLock()
188
+ INSTANCES: WeakValueDictionary[int, HostProcess] = WeakValueDictionary()
189
+
190
+ _pid: int
191
+ _super_gone: bool
192
+ _username: str | None
193
+ _ident: tuple
194
+ _lock: threading.RLock
195
+
196
+ def __new__(cls, pid: int | None = None) -> Self:
197
+ """Return the cached instance of :class:`HostProcess`."""
198
+ if pid is None:
199
+ pid = os.getpid()
200
+
201
+ with cls.INSTANCE_LOCK:
202
+ try:
203
+ instance = cls.INSTANCES[pid]
204
+ if instance.is_running():
205
+ return instance
206
+ except KeyError:
207
+ pass
208
+
209
+ instance = super().__new__(cls)
210
+
211
+ instance._super_gone = False
212
+ instance._username = None
213
+ host.Process._init(instance, pid, True)
214
+ try:
215
+ host.Process.cpu_percent(instance)
216
+ except host.PsutilError:
217
+ pass
218
+
219
+ cls.INSTANCES[pid] = instance
220
+
221
+ return instance
222
+
223
+ # pylint: disable-next=unused-argument,super-init-not-called
224
+ def __init__(self, pid: int | None = None) -> None:
225
+ """Initialize the instance."""
226
+
227
+ @property
228
+ def _gone(self) -> bool:
229
+ return self._super_gone
230
+
231
+ @_gone.setter
232
+ def _gone(self, value: bool) -> None:
233
+ if value:
234
+ with self.INSTANCE_LOCK:
235
+ self.INSTANCES.pop(self.pid, None)
236
+ self._super_gone = value
237
+
238
+ def __repr__(self) -> str:
239
+ """Return a string representation of the process."""
240
+ return super().__repr__().replace(f'{self.__class__.__module__}.', '', 1)
241
+
242
+ def __reduce__(self) -> tuple[type[HostProcess], tuple[int]]:
243
+ """Return state information for pickling."""
244
+ return self.__class__, (self.pid,)
245
+
246
+ if host.WINDOWS:
247
+
248
+ def username(self) -> str:
249
+ """The name of the user that owns the process.
250
+
251
+ On Windows, the domain name will be removed if it is present.
252
+
253
+ Raises:
254
+ host.NoSuchProcess:
255
+ If the process is gone.
256
+ host.AccessDenied:
257
+ If the user do not have read privilege to the process' status file.
258
+ """
259
+ if self._username is None: # pylint: disable=access-member-before-definition
260
+ self._username = ( # pylint: disable=attribute-defined-outside-init
261
+ super().username().split('\\')[-1]
262
+ )
263
+ return self._username
264
+
265
+ else:
266
+
267
+ def username(self) -> str:
268
+ """The name of the user that owns the process.
269
+
270
+ On UNIX this is calculated by using *real* process uid.
271
+
272
+ Raises:
273
+ host.NoSuchProcess:
274
+ If the process is gone.
275
+ host.AccessDenied:
276
+ If the user do not have read privilege to the process' status file.
277
+ """
278
+ if self._username is None: # pylint: disable=access-member-before-definition
279
+ self._username = ( # pylint: disable=attribute-defined-outside-init
280
+ super().username()
281
+ )
282
+ return self._username
283
+
284
+ @memoize_when_activated
285
+ def cmdline(self) -> list[str]:
286
+ """The command line this process has been called with.
287
+
288
+ Raises:
289
+ host.NoSuchProcess:
290
+ If the process is gone.
291
+ host.AccessDenied:
292
+ If the user do not have read privilege to the process' status file.
293
+ """
294
+ cmdline = super().cmdline()
295
+ if len(cmdline) > 1:
296
+ cmdline = '\0'.join(cmdline).rstrip('\0').split('\0')
297
+ return cmdline
298
+
299
+ def command(self) -> str:
300
+ """Return a shell-escaped string from command line arguments.
301
+
302
+ Raises:
303
+ host.NoSuchProcess:
304
+ If the process is gone.
305
+ host.AccessDenied:
306
+ If the user do not have read privilege to the process' status file.
307
+ """
308
+ return command_join(self.cmdline())
309
+
310
+ @memoize_when_activated
311
+ def running_time(self) -> datetime.timedelta:
312
+ """The elapsed time this process has been running in :class:`datetime.timedelta`.
313
+
314
+ Raises:
315
+ host.NoSuchProcess:
316
+ If the process is gone.
317
+ host.AccessDenied:
318
+ If the user do not have read privilege to the process' status file.
319
+ """
320
+ return datetime.datetime.now() - datetime.datetime.fromtimestamp(self.create_time())
321
+
322
+ def running_time_human(self) -> str:
323
+ """The elapsed time this process has been running in human readable format.
324
+
325
+ Raises:
326
+ host.NoSuchProcess:
327
+ If the process is gone.
328
+ host.AccessDenied:
329
+ If the user do not have read privilege to the process' status file.
330
+ """
331
+ return timedelta2human(self.running_time())
332
+
333
+ def running_time_in_seconds(self) -> float: # in seconds
334
+ """The elapsed time this process has been running in seconds.
335
+
336
+ Raises:
337
+ host.NoSuchProcess:
338
+ If the process is gone.
339
+ host.AccessDenied:
340
+ If the user do not have read privilege to the process' status file.
341
+ """
342
+ return self.running_time().total_seconds()
343
+
344
+ elapsed_time = running_time
345
+ elapsed_time_human = running_time_human
346
+ elapsed_time_in_seconds = running_time_in_seconds
347
+
348
+ def rss_memory(self) -> int: # in bytes
349
+ """The used resident set size (RSS) memory of the process in bytes.
350
+
351
+ Raises:
352
+ host.NoSuchProcess:
353
+ If the process is gone.
354
+ host.AccessDenied:
355
+ If the user do not have read privilege to the process' status file.
356
+ """
357
+ return self.memory_info().rss
358
+
359
+ def parent(self) -> HostProcess | None:
360
+ """Return the parent process as a :class:`HostProcess` instance or :data:`None` if there is no parent.
361
+
362
+ Raises:
363
+ host.NoSuchProcess:
364
+ If the process is gone.
365
+ host.AccessDenied:
366
+ If the user do not have read privilege to the process' status file.
367
+ """
368
+ parent = super().parent()
369
+ if parent is not None:
370
+ return HostProcess(parent.pid)
371
+ return None
372
+
373
+ def children(self, recursive: bool = False) -> list[HostProcess]:
374
+ """Return the children of this process as a list of :class:`HostProcess` instances.
375
+
376
+ If *recursive* is :data:`True` return all the descendants.
377
+
378
+ Raises:
379
+ host.NoSuchProcess:
380
+ If the process is gone.
381
+ host.AccessDenied:
382
+ If the user do not have read privilege to the process' status file.
383
+ """
384
+ return [HostProcess(child.pid) for child in super().children(recursive)]
385
+
386
+ @contextlib.contextmanager
387
+ def oneshot(self) -> Generator[None]:
388
+ """A utility context manager which considerably speeds up the retrieval of multiple process information at the same time.
389
+
390
+ Internally different process info (e.g. name, ppid, uids, gids, ...) may be fetched by using
391
+ the same routine, but only one information is returned and the others are discarded. When
392
+ using this context manager the internal routine is executed once (in the example below on
393
+ ``name()``) and the other info are cached.
394
+
395
+ The cache is cleared when exiting the context manager block. The advice is to use this every
396
+ time you retrieve more than one information about the process.
397
+
398
+ Examples:
399
+ >>> from nvitop import HostProcess
400
+ >>> p = HostProcess()
401
+ >>> with p.oneshot():
402
+ ... p.name() # collect multiple info
403
+ ... p.cpu_times() # return cached value
404
+ ... p.cpu_percent() # return cached value
405
+ ... p.create_time() # return cached value
406
+ """ # pylint: disable=line-too-long
407
+ with self._lock:
408
+ if hasattr(self, '_cache'):
409
+ yield
410
+ else:
411
+ with super().oneshot():
412
+ # pylint: disable=no-member
413
+ try:
414
+ self.cmdline.cache_activate(self) # type: ignore[attr-defined]
415
+ self.running_time.cache_activate(self) # type: ignore[attr-defined]
416
+ yield
417
+ finally:
418
+ self.cmdline.cache_deactivate(self) # type: ignore[attr-defined]
419
+ self.running_time.cache_deactivate(self) # type: ignore[attr-defined]
420
+
421
+ def as_snapshot(
422
+ self,
423
+ attrs: Iterable[str] | None = None,
424
+ ad_value: Any | None = None,
425
+ ) -> Snapshot:
426
+ """Return a onetime snapshot of the process."""
427
+ with self.oneshot():
428
+ attributes = self.as_dict(attrs=attrs, ad_value=ad_value)
429
+
430
+ if attrs is None:
431
+ for attr in ('command', 'running_time', 'running_time_human'):
432
+ try:
433
+ attributes[attr] = getattr(self, attr)()
434
+ except (host.AccessDenied, host.ZombieProcess): # noqa: PERF203
435
+ attributes[attr] = ad_value
436
+
437
+ return Snapshot(real=self, **attributes)
438
+
439
+
440
+ @HostProcess.register
441
+ class GpuProcess: # pylint: disable=too-many-instance-attributes,too-many-public-methods
442
+ """Represent a process with the given PID running on the given GPU device.
443
+
444
+ The instance will be cache during the lifetime of the process.
445
+
446
+ The same host process can use multiple GPU devices. The :class:`GpuProcess` instances
447
+ representing the same PID on the host but different GPU devices are different.
448
+ """
449
+
450
+ INSTANCE_LOCK: threading.RLock = threading.RLock()
451
+ INSTANCES: WeakValueDictionary[tuple[int, Device], GpuProcess] = WeakValueDictionary()
452
+
453
+ _pid: int
454
+ _host: HostProcess
455
+ _device: Device
456
+ _username: str | None
457
+ _ident: tuple
458
+ _hash: int | None
459
+
460
+ # pylint: disable-next=too-many-arguments,unused-argument
461
+ def __new__(
462
+ cls,
463
+ pid: int | None,
464
+ device: Device,
465
+ *,
466
+ gpu_memory: int | NaType | None = None,
467
+ gpu_instance_id: int | NaType | None = None,
468
+ compute_instance_id: int | NaType | None = None,
469
+ type: str | NaType | None = None, # pylint: disable=redefined-builtin
470
+ ) -> Self:
471
+ """Return the cached instance of :class:`GpuProcess`."""
472
+ if pid is None:
473
+ pid = os.getpid()
474
+
475
+ with cls.INSTANCE_LOCK:
476
+ try:
477
+ instance = cls.INSTANCES[pid, device]
478
+ if instance.is_running():
479
+ return instance # type: ignore[return-value]
480
+ except KeyError:
481
+ pass
482
+
483
+ instance = super().__new__(cls)
484
+
485
+ instance._pid = pid
486
+ instance._host = HostProcess(pid)
487
+ instance._ident = (*instance._host._ident, device.index)
488
+ instance._device = device
489
+
490
+ instance._hash = None
491
+ instance._username = None
492
+
493
+ cls.INSTANCES[pid, device] = instance
494
+
495
+ return instance
496
+
497
+ # pylint: disable-next=too-many-arguments
498
+ def __init__(
499
+ self,
500
+ pid: int | None, # pylint: disable=unused-argument
501
+ device: Device,
502
+ *,
503
+ gpu_memory: int | NaType | None = None,
504
+ gpu_instance_id: int | NaType | None = None,
505
+ compute_instance_id: int | NaType | None = None,
506
+ type: str | NaType | None = None, # pylint: disable=redefined-builtin
507
+ ) -> None:
508
+ """Initialize the instance returned by :meth:`__new__()`."""
509
+ if gpu_memory is None and not hasattr(self, '_gpu_memory'):
510
+ gpu_memory = NA
511
+ if gpu_memory is not None:
512
+ self.set_gpu_memory(gpu_memory)
513
+
514
+ if type is None and not hasattr(self, '_type'):
515
+ type = NA
516
+ if type is not None:
517
+ self.type = type
518
+
519
+ if gpu_instance_id is not None and compute_instance_id is not None:
520
+ self._gpu_instance_id = gpu_instance_id if gpu_instance_id != UINT_MAX else NA
521
+ self._compute_instance_id = (
522
+ compute_instance_id if compute_instance_id != UINT_MAX else NA
523
+ )
524
+ elif device.is_mig_device():
525
+ self._gpu_instance_id = device.gpu_instance_id()
526
+ self._compute_instance_id = device.compute_instance_id()
527
+ else:
528
+ self._gpu_instance_id = self._compute_instance_id = NA
529
+
530
+ for util in ('sm', 'memory', 'encoder', 'decoder'):
531
+ if not hasattr(self, f'_gpu_{util}_utilization'):
532
+ setattr(self, f'_gpu_{util}_utilization', NA)
533
+
534
+ def __repr__(self) -> str:
535
+ """Return a string representation of the GPU process."""
536
+ return '{}(pid={}, gpu_memory={}, type={}, device={}, host={})'.format( # noqa: UP032
537
+ self.__class__.__name__,
538
+ self.pid,
539
+ self.gpu_memory_human(),
540
+ self.type,
541
+ self.device,
542
+ self.host,
543
+ )
544
+
545
+ def __eq__(self, other: object) -> bool:
546
+ """Test equality to other object."""
547
+ if not isinstance(other, (GpuProcess, host.Process)):
548
+ return NotImplemented
549
+ return self._ident == other._ident
550
+
551
+ def __hash__(self) -> int:
552
+ """Return a hash value of the GPU process."""
553
+ if self._hash is None: # pylint: disable=access-member-before-definition
554
+ self._hash = hash(self._ident) # pylint: disable=attribute-defined-outside-init
555
+ return self._hash
556
+
557
+ def __getattr__(self, name: str) -> Any | Callable[..., Any]:
558
+ """Get a member from the instance or fallback to the host process instance if missing.
559
+
560
+ Raises:
561
+ AttributeError:
562
+ If the attribute is not defined in either :class:`GpuProcess` nor :class:`HostProcess`.
563
+ host.NoSuchProcess:
564
+ If the process is gone.
565
+ host.AccessDenied:
566
+ If the user do not have read privilege to the process' status file.
567
+ """
568
+ try:
569
+ return super().__getattr__(name) # type: ignore[misc]
570
+ except AttributeError:
571
+ if name == '_cache':
572
+ raise
573
+ attribute = getattr(self.host, name)
574
+ if isinstance(attribute, FunctionType):
575
+ attribute = auto_garbage_clean(fallback=_RAISE)(attribute)
576
+
577
+ setattr(self, name, attribute)
578
+ return attribute
579
+
580
+ @property
581
+ def pid(self) -> int:
582
+ """The process PID."""
583
+ return self._pid
584
+
585
+ @property
586
+ def host(self) -> HostProcess:
587
+ """The process instance running on the host."""
588
+ return self._host
589
+
590
+ @property
591
+ def device(self) -> Device:
592
+ """The GPU device the process running on.
593
+
594
+ The same host process can use multiple GPU devices. The :class:`GpuProcess` instances
595
+ representing the same PID on the host but different GPU devices are different.
596
+ """
597
+ return self._device
598
+
599
+ def gpu_instance_id(self) -> int | NaType:
600
+ """The GPU instance ID of the MIG device, or :const:`nvitop.NA` if not applicable."""
601
+ return self._gpu_instance_id
602
+
603
+ def compute_instance_id(self) -> int | NaType:
604
+ """The compute instance ID of the MIG device, or :const:`nvitop.NA` if not applicable."""
605
+ return self._compute_instance_id
606
+
607
+ def gpu_memory(self) -> int | NaType: # in bytes
608
+ """The used GPU memory in bytes, or :const:`nvitop.NA` if not applicable."""
609
+ return self._gpu_memory
610
+
611
+ def gpu_memory_human(self) -> str | NaType: # in human readable
612
+ """The used GPU memory in human readable format, or :const:`nvitop.NA` if not applicable."""
613
+ return self._gpu_memory_human
614
+
615
+ def gpu_memory_percent(self) -> float | NaType: # in percentage
616
+ """The percentage of used GPU memory by the process, or :const:`nvitop.NA` if not applicable."""
617
+ return self._gpu_memory_percent
618
+
619
+ def gpu_sm_utilization(self) -> int | NaType: # in percentage
620
+ """The utilization rate of SM (Streaming Multiprocessor), or :const:`nvitop.NA` if not applicable."""
621
+ return self._gpu_sm_utilization
622
+
623
+ def gpu_memory_utilization(self) -> int | NaType: # in percentage
624
+ """The utilization rate of GPU memory bandwidth, or :const:`nvitop.NA` if not applicable."""
625
+ return self._gpu_memory_utilization
626
+
627
+ def gpu_encoder_utilization(self) -> int | NaType: # in percentage
628
+ """The utilization rate of the encoder, or :const:`nvitop.NA` if not applicable."""
629
+ return self._gpu_encoder_utilization
630
+
631
+ def gpu_decoder_utilization(self) -> int | NaType: # in percentage
632
+ """The utilization rate of the decoder, or :const:`nvitop.NA` if not applicable."""
633
+ return self._gpu_decoder_utilization
634
+
635
+ def set_gpu_memory(self, value: int | NaType) -> None:
636
+ """Set the used GPU memory in bytes."""
637
+ # pylint: disable=attribute-defined-outside-init
638
+ self._gpu_memory = memory_used = value
639
+ self._gpu_memory_human = bytes2human(self.gpu_memory())
640
+ memory_total = self.device.memory_total()
641
+ gpu_memory_percent = NA
642
+ if libnvml.nvmlCheckReturn(memory_used, int) and libnvml.nvmlCheckReturn(memory_total, int):
643
+ gpu_memory_percent = round(100.0 * memory_used / memory_total, 1) # type: ignore[assignment]
644
+ self._gpu_memory_percent = gpu_memory_percent
645
+
646
+ def set_gpu_utilization(
647
+ self,
648
+ gpu_sm_utilization: int | NaType | None = None,
649
+ gpu_memory_utilization: int | NaType | None = None,
650
+ gpu_encoder_utilization: int | NaType | None = None,
651
+ gpu_decoder_utilization: int | NaType | None = None,
652
+ ) -> None:
653
+ """Set the GPU utilization rates."""
654
+ # pylint: disable=attribute-defined-outside-init
655
+ if gpu_sm_utilization is not None:
656
+ self._gpu_sm_utilization = gpu_sm_utilization
657
+ if gpu_memory_utilization is not None:
658
+ self._gpu_memory_utilization = gpu_memory_utilization
659
+ if gpu_encoder_utilization is not None:
660
+ self._gpu_encoder_utilization = gpu_encoder_utilization
661
+ if gpu_decoder_utilization is not None:
662
+ self._gpu_decoder_utilization = gpu_decoder_utilization
663
+
664
+ def update_gpu_status(self) -> int | NaType:
665
+ """Update the GPU consumption status from a new NVML query."""
666
+ self.set_gpu_memory(NA)
667
+ self.set_gpu_utilization(NA, NA, NA, NA)
668
+ processes = self.device.processes()
669
+ process = processes.get(self.pid, self)
670
+ if process is not self:
671
+ # The current process is gone and the instance has been removed from the cache.
672
+ # Update GPU status from the new instance.
673
+ self.set_gpu_memory(process.gpu_memory())
674
+ self.set_gpu_utilization(
675
+ process.gpu_sm_utilization(),
676
+ process.gpu_memory_utilization(),
677
+ process.gpu_encoder_utilization(),
678
+ process.gpu_decoder_utilization(),
679
+ )
680
+ return self.gpu_memory()
681
+
682
+ @property
683
+ def type(self) -> str | NaType:
684
+ """The type of the GPU context.
685
+
686
+ The type is one of the following:
687
+ - :data:`'C'`: compute context
688
+ - :data:`'G'`: graphics context
689
+ - :data:`'C+G'`: both compute context and graphics context
690
+ - :data:`'N/A'`: not applicable
691
+ """
692
+ return self._type
693
+
694
+ @type.setter
695
+ def type(self, value: str | NaType) -> None:
696
+ if 'C' in value and 'G' in value:
697
+ self._type = 'C+G'
698
+ elif 'C' in value:
699
+ self._type = 'C'
700
+ elif 'G' in value:
701
+ self._type = 'G'
702
+ else:
703
+ self._type = NA
704
+
705
+ @auto_garbage_clean(fallback=False)
706
+ def is_running(self) -> bool:
707
+ """Return whether this process is running."""
708
+ return self.host.is_running()
709
+
710
+ @auto_garbage_clean(fallback='terminated')
711
+ def status(self) -> str:
712
+ """The process current status.
713
+
714
+ Raises:
715
+ host.NoSuchProcess:
716
+ If the process is gone.
717
+ host.AccessDenied:
718
+ If the user do not have read privilege to the process' status file.
719
+
720
+ Note:
721
+ To return the fallback value rather than raise an exception, please use the context
722
+ manager :meth:`GpuProcess.failsafe`. See also :meth:`take_snapshots` and :meth:`failsafe`.
723
+ """
724
+ return self.host.status()
725
+
726
+ @auto_garbage_clean(fallback=NA)
727
+ def create_time(self) -> float | NaType:
728
+ """The process creation time as a floating point number expressed in seconds since the epoch.
729
+
730
+ Raises:
731
+ host.NoSuchProcess:
732
+ If the process is gone.
733
+ host.AccessDenied:
734
+ If the user do not have read privilege to the process' status file.
735
+
736
+ Note:
737
+ To return the fallback value rather than raise an exception, please use the context
738
+ manager :meth:`GpuProcess.failsafe`. See also :meth:`take_snapshots` and :meth:`failsafe`.
739
+ """
740
+ return self.host.create_time()
741
+
742
+ @auto_garbage_clean(fallback=NA)
743
+ def running_time(self) -> datetime.timedelta | NaType:
744
+ """The elapsed time this process has been running in :class:`datetime.timedelta`.
745
+
746
+ Raises:
747
+ host.NoSuchProcess:
748
+ If the process is gone.
749
+ host.AccessDenied:
750
+ If the user do not have read privilege to the process' status file.
751
+
752
+ Note:
753
+ To return the fallback value rather than raise an exception, please use the context
754
+ manager :meth:`GpuProcess.failsafe`. See also :meth:`take_snapshots` and :meth:`failsafe`.
755
+ """
756
+ return self.host.running_time()
757
+
758
+ def running_time_human(self) -> str | NaType:
759
+ """The elapsed time this process has been running in human readable format.
760
+
761
+ Raises:
762
+ host.NoSuchProcess:
763
+ If the process is gone.
764
+ host.AccessDenied:
765
+ If the user do not have read privilege to the process' status file.
766
+
767
+ Note:
768
+ To return the fallback value rather than raise an exception, please use the context
769
+ manager :meth:`GpuProcess.failsafe`. See also :meth:`take_snapshots` and :meth:`failsafe`.
770
+ """
771
+ return timedelta2human(self.running_time())
772
+
773
+ def running_time_in_seconds(self) -> float | NaType:
774
+ """The elapsed time this process has been running in seconds.
775
+
776
+ Raises:
777
+ host.NoSuchProcess:
778
+ If the process is gone.
779
+ host.AccessDenied:
780
+ If the user do not have read privilege to the process' status file.
781
+
782
+ Note:
783
+ To return the fallback value rather than raise an exception, please use the context
784
+ manager :meth:`GpuProcess.failsafe`. See also :meth:`take_snapshots` and :meth:`failsafe`.
785
+ """
786
+ running_time = self.running_time()
787
+ if running_time is NA:
788
+ return NA
789
+ return running_time.total_seconds()
790
+
791
+ elapsed_time = running_time
792
+ elapsed_time_human = running_time_human
793
+ elapsed_time_in_seconds = running_time_in_seconds
794
+
795
+ @auto_garbage_clean(fallback=NA)
796
+ def username(self) -> str | NaType:
797
+ """The name of the user that owns the process.
798
+
799
+ Raises:
800
+ host.NoSuchProcess:
801
+ If the process is gone.
802
+ host.AccessDenied:
803
+ If the user do not have read privilege to the process' status file.
804
+
805
+ Note:
806
+ To return the fallback value rather than raise an exception, please use the context
807
+ manager :meth:`GpuProcess.failsafe`. See also :meth:`take_snapshots` and :meth:`failsafe`.
808
+ """
809
+ if self._username is None: # pylint: disable=access-member-before-definition
810
+ self._username = self.host.username() # pylint: disable=attribute-defined-outside-init
811
+ return self._username
812
+
813
+ @auto_garbage_clean(fallback=NA)
814
+ def name(self) -> str | NaType:
815
+ """The process name.
816
+
817
+ Raises:
818
+ host.NoSuchProcess:
819
+ If the process is gone.
820
+ host.AccessDenied:
821
+ If the user do not have read privilege to the process' status file.
822
+
823
+ Note:
824
+ To return the fallback value rather than raise an exception, please use the context
825
+ manager :meth:`GpuProcess.failsafe`. See also :meth:`take_snapshots` and :meth:`failsafe`.
826
+ """
827
+ return self.host.name()
828
+
829
+ @auto_garbage_clean(fallback=NA)
830
+ def cpu_percent(self) -> float | NaType: # in percentage
831
+ """Return a float representing the current process CPU utilization as a percentage.
832
+
833
+ Raises:
834
+ host.NoSuchProcess:
835
+ If the process is gone.
836
+ host.AccessDenied:
837
+ If the user do not have read privilege to the process' status file.
838
+
839
+ Note:
840
+ To return the fallback value rather than raise an exception, please use the context
841
+ manager :meth:`GpuProcess.failsafe`. See also :meth:`take_snapshots` and :meth:`failsafe`.
842
+ """
843
+ return self.host.cpu_percent()
844
+
845
+ @auto_garbage_clean(fallback=NA)
846
+ def memory_percent(self) -> float | NaType: # in percentage
847
+ """Compare process RSS memory to total physical system memory and calculate process memory utilization as a percentage.
848
+
849
+ Raises:
850
+ host.NoSuchProcess:
851
+ If the process is gone.
852
+ host.AccessDenied:
853
+ If the user do not have read privilege to the process' status file.
854
+
855
+ Note:
856
+ To return the fallback value rather than raise an exception, please use the context
857
+ manager :meth:`GpuProcess.failsafe`. See also :meth:`take_snapshots` and :meth:`failsafe`.
858
+ """ # pylint: disable=line-too-long
859
+ return self.host.memory_percent()
860
+
861
+ host_memory_percent = memory_percent # in percentage
862
+
863
+ @auto_garbage_clean(fallback=NA)
864
+ def host_memory(self) -> int | NaType: # in bytes
865
+ """The used resident set size (RSS) memory of the process in bytes.
866
+
867
+ Raises:
868
+ host.NoSuchProcess:
869
+ If the process is gone.
870
+ host.AccessDenied:
871
+ If the user do not have read privilege to the process' status file.
872
+
873
+ Note:
874
+ To return the fallback value rather than raise an exception, please use the context
875
+ manager :meth:`GpuProcess.failsafe`. See also :meth:`take_snapshots` and :meth:`failsafe`.
876
+ """
877
+ return self.host.rss_memory()
878
+
879
+ def host_memory_human(self) -> str | NaType:
880
+ """The used resident set size (RSS) memory of the process in human readable format.
881
+
882
+ Raises:
883
+ host.NoSuchProcess:
884
+ If the process is gone.
885
+ host.AccessDenied:
886
+ If the user do not have read privilege to the process' status file.
887
+
888
+ Note:
889
+ To return the fallback value rather than raise an exception, please use the context
890
+ manager :meth:`GpuProcess.failsafe`. See also :meth:`take_snapshots` and :meth:`failsafe`.
891
+ """
892
+ return bytes2human(self.host_memory())
893
+
894
+ rss_memory = host_memory # in bytes
895
+
896
+ # For `AccessDenied` error the fallback value is `['No Permissions']`
897
+ @auto_garbage_clean(fallback=('No Such Process',))
898
+ def cmdline(self) -> list[str]:
899
+ """The command line this process has been called with.
900
+
901
+ Raises:
902
+ host.NoSuchProcess:
903
+ If the process is gone.
904
+ host.AccessDenied:
905
+ If the user do not have read privilege to the process' status file.
906
+
907
+ Note:
908
+ To return the fallback value rather than raise an exception, please use the context
909
+ manager :meth:`GpuProcess.failsafe`. See also :meth:`take_snapshots` and :meth:`failsafe`.
910
+ """
911
+ cmdline = self.host.cmdline()
912
+ if len(cmdline) == 0 and not self._gone:
913
+ cmdline = ['Zombie Process']
914
+ return cmdline
915
+
916
+ def command(self) -> str:
917
+ """Return a shell-escaped string from command line arguments.
918
+
919
+ Raises:
920
+ host.NoSuchProcess:
921
+ If the process is gone.
922
+ host.AccessDenied:
923
+ If the user do not have read privilege to the process' status file.
924
+
925
+ Note:
926
+ To return the fallback value rather than raise an exception, please use the context
927
+ manager :meth:`GpuProcess.failsafe`. See also :meth:`take_snapshots` and :meth:`failsafe`.
928
+ """
929
+ return command_join(self.cmdline())
930
+
931
+ @auto_garbage_clean(fallback=_RAISE)
932
+ def host_snapshot(self) -> Snapshot:
933
+ """Return a onetime snapshot of the host process."""
934
+ with self.host.oneshot():
935
+ return Snapshot(
936
+ real=self.host,
937
+ is_running=self.is_running(),
938
+ status=self.status(),
939
+ username=self.username(),
940
+ name=self.name(),
941
+ cmdline=self.cmdline(),
942
+ command=self.command(),
943
+ cpu_percent=self.cpu_percent(),
944
+ memory_percent=self.memory_percent(),
945
+ host_memory=self.host_memory(),
946
+ host_memory_human=self.host_memory_human(),
947
+ running_time=self.running_time(),
948
+ running_time_human=self.running_time_human(),
949
+ running_time_in_seconds=self.running_time_in_seconds(),
950
+ )
951
+
952
+ @auto_garbage_clean(fallback=_RAISE)
953
+ def as_snapshot(
954
+ self,
955
+ *,
956
+ host_process_snapshot_cache: dict[int, Snapshot] | None = None,
957
+ ) -> Snapshot:
958
+ """Return a onetime snapshot of the process on the GPU device.
959
+
960
+ Note:
961
+ To return the fallback value rather than raise an exception, please use the context
962
+ manager :meth:`GpuProcess.failsafe`. Also, consider using the batched version to take
963
+ snapshots with :meth:`GpuProcess.take_snapshots`, which caches the results and reduces
964
+ redundant queries. See also :meth:`take_snapshots` and :meth:`failsafe`.
965
+ """
966
+ if host_process_snapshot_cache is None:
967
+ host_process_snapshot_cache = {}
968
+ try:
969
+ host_snapshot = host_process_snapshot_cache[self.pid]
970
+ except KeyError:
971
+ host_snapshot = host_process_snapshot_cache[self.pid] = self.host_snapshot()
972
+
973
+ return Snapshot(
974
+ real=self,
975
+ pid=self.pid,
976
+ # host
977
+ host=host_snapshot,
978
+ is_running=host_snapshot.is_running,
979
+ status=host_snapshot.status,
980
+ username=host_snapshot.username,
981
+ name=host_snapshot.name,
982
+ cmdline=host_snapshot.cmdline,
983
+ command=host_snapshot.command,
984
+ cpu_percent=host_snapshot.cpu_percent,
985
+ memory_percent=host_snapshot.memory_percent,
986
+ host_memory=host_snapshot.host_memory,
987
+ host_memory_human=host_snapshot.host_memory_human,
988
+ running_time=host_snapshot.running_time,
989
+ running_time_human=host_snapshot.running_time_human,
990
+ running_time_in_seconds=host_snapshot.running_time_in_seconds,
991
+ # device
992
+ device=self.device,
993
+ type=self.type,
994
+ gpu_instance_id=self.gpu_instance_id(),
995
+ compute_instance_id=self.compute_instance_id(),
996
+ gpu_memory=self.gpu_memory(),
997
+ gpu_memory_human=self.gpu_memory_human(),
998
+ gpu_memory_percent=self.gpu_memory_percent(),
999
+ gpu_sm_utilization=self.gpu_sm_utilization(),
1000
+ gpu_memory_utilization=self.gpu_memory_utilization(),
1001
+ gpu_encoder_utilization=self.gpu_encoder_utilization(),
1002
+ gpu_decoder_utilization=self.gpu_decoder_utilization(),
1003
+ )
1004
+
1005
+ @classmethod
1006
+ def take_snapshots( # batched version of `as_snapshot`
1007
+ cls,
1008
+ gpu_processes: Iterable[GpuProcess],
1009
+ *,
1010
+ failsafe: bool = False,
1011
+ ) -> list[Snapshot]:
1012
+ """Take snapshots for a list of :class:`GpuProcess` instances.
1013
+
1014
+ If *failsafe* is :data:`True`, then if any method fails, the fallback value in
1015
+ :func:`auto_garbage_clean` will be used.
1016
+ """
1017
+ cache: dict[int, Snapshot] = {}
1018
+ context: Callable[[], contextlib.AbstractContextManager[None]] = (
1019
+ cls.failsafe if failsafe else contextlib.nullcontext
1020
+ )
1021
+ with context():
1022
+ return [
1023
+ process.as_snapshot(host_process_snapshot_cache=cache) for process in gpu_processes
1024
+ ]
1025
+
1026
+ @classmethod
1027
+ @contextlib.contextmanager
1028
+ def failsafe(cls) -> Generator[None]:
1029
+ """A context manager that enables fallback values for methods that fail.
1030
+
1031
+ Examples:
1032
+ >>> p = GpuProcess(pid=10000, device=Device(0)) # process does not exist
1033
+ >>> p
1034
+ GpuProcess(pid=10000, gpu_memory=N/A, type=N/A, device=PhysicalDevice(index=0, name="NVIDIA GeForce RTX 3070", total_memory=8192MiB), host=HostProcess(pid=10000, status='terminated'))
1035
+ >>> p.cpu_percent()
1036
+ Traceback (most recent call last):
1037
+ ...
1038
+ NoSuchProcess: process no longer exists (pid=10000)
1039
+
1040
+ >>> # Failsafe to the fallback value instead of raising exceptions
1041
+ ... with GpuProcess.failsafe():
1042
+ ... print('fallback: {!r}'.format(p.cpu_percent()))
1043
+ ... print('fallback (float cast): {!r}'.format(float(p.cpu_percent()))) # `nvitop.NA` can be cast to float or int
1044
+ ... print('fallback (int cast): {!r}'.format(int(p.cpu_percent()))) # `nvitop.NA` can be cast to float or int
1045
+ fallback: 'N/A'
1046
+ fallback (float cast): nan
1047
+ fallback (int cast): 0
1048
+ """ # pylint: disable=line-too-long
1049
+ global _USE_FALLBACK_WHEN_RAISE # pylint: disable=global-statement,global-variable-not-assigned
1050
+
1051
+ prev_value = getattr(_USE_FALLBACK_WHEN_RAISE, 'value', False)
1052
+ try:
1053
+ _USE_FALLBACK_WHEN_RAISE.value = True
1054
+ yield
1055
+ finally:
1056
+ _USE_FALLBACK_WHEN_RAISE.value = prev_value
.venv/lib/python3.10/site-packages/nvitop/api/termcolor.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is part of nvitop, the interactive NVIDIA-GPU process viewer.
2
+ #
3
+ # Copyright 2021-2025 Xuehai Pan. All Rights Reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ # ==============================================================================
17
+ # pylint: disable=wrong-spelling-in-comment
18
+ # Vendored from the `termcolor` package: https://github.com/termcolor/termcolor
19
+ # ==============================================================================
20
+ # Copyright (c) 2008-2011 Volvox Development Team
21
+ #
22
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
23
+ # of this software and associated documentation files (the "Software"), to deal
24
+ # in the Software without restriction, including without limitation the rights
25
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
26
+ # copies of the Software, and to permit persons to whom the Software is
27
+ # furnished to do so, subject to the following conditions:
28
+ #
29
+ # The above copyright notice and this permission notice shall be included in
30
+ # all copies or substantial portions of the Software.
31
+ #
32
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
33
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
34
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
35
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
36
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
37
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
38
+ # THE SOFTWARE.
39
+ #
40
+ # Author: Konstantin Lepa <[email protected]>
41
+ # ==============================================================================
42
+ """ANSI color formatting for output in terminal."""
43
+
44
+ from __future__ import annotations
45
+
46
+ import io
47
+ import os
48
+ import sys
49
+ from typing import TYPE_CHECKING, Any, Literal
50
+
51
+
52
+ if TYPE_CHECKING:
53
+ from collections.abc import Iterable
54
+
55
+ Attribute = Literal[
56
+ 'bold',
57
+ 'dark',
58
+ 'underline',
59
+ 'blink',
60
+ 'reverse',
61
+ 'concealed',
62
+ 'strike',
63
+ ]
64
+ Highlight = Literal[
65
+ 'on_black',
66
+ 'on_grey',
67
+ 'on_red',
68
+ 'on_green',
69
+ 'on_yellow',
70
+ 'on_blue',
71
+ 'on_magenta',
72
+ 'on_cyan',
73
+ 'on_light_grey',
74
+ 'on_dark_grey',
75
+ 'on_light_red',
76
+ 'on_light_green',
77
+ 'on_light_yellow',
78
+ 'on_light_blue',
79
+ 'on_light_magenta',
80
+ 'on_light_cyan',
81
+ 'on_white',
82
+ ]
83
+ Color = Literal[
84
+ 'black',
85
+ 'grey',
86
+ 'red',
87
+ 'green',
88
+ 'yellow',
89
+ 'blue',
90
+ 'magenta',
91
+ 'cyan',
92
+ 'light_grey',
93
+ 'dark_grey',
94
+ 'light_red',
95
+ 'light_green',
96
+ 'light_yellow',
97
+ 'light_blue',
98
+ 'light_magenta',
99
+ 'light_cyan',
100
+ 'white',
101
+ ]
102
+
103
+
104
+ __all__ = ['colored', 'cprint']
105
+
106
+
107
+ if os.name == 'nt': # Windows
108
+ try:
109
+ from colorama import init
110
+ except ImportError:
111
+ pass
112
+ else:
113
+ init()
114
+
115
+
116
+ ATTRIBUTES: dict[Attribute, int] = {
117
+ 'bold': 1,
118
+ 'dark': 2,
119
+ 'underline': 4,
120
+ 'blink': 5,
121
+ 'reverse': 7,
122
+ 'concealed': 8,
123
+ 'strike': 9,
124
+ }
125
+
126
+ HIGHLIGHTS: dict[Highlight, int] = {
127
+ 'on_black': 40,
128
+ 'on_grey': 40, # Actually black but kept for backwards compatibility
129
+ 'on_red': 41,
130
+ 'on_green': 42,
131
+ 'on_yellow': 43,
132
+ 'on_blue': 44,
133
+ 'on_magenta': 45,
134
+ 'on_cyan': 46,
135
+ 'on_light_grey': 47,
136
+ 'on_dark_grey': 100,
137
+ 'on_light_red': 101,
138
+ 'on_light_green': 102,
139
+ 'on_light_yellow': 103,
140
+ 'on_light_blue': 104,
141
+ 'on_light_magenta': 105,
142
+ 'on_light_cyan': 106,
143
+ 'on_white': 107,
144
+ }
145
+
146
+ COLORS: dict[Color, int] = {
147
+ 'black': 30,
148
+ 'grey': 30, # Actually black but kept for backwards compatibility
149
+ 'red': 31,
150
+ 'green': 32,
151
+ 'yellow': 33,
152
+ 'blue': 34,
153
+ 'magenta': 35,
154
+ 'cyan': 36,
155
+ 'light_grey': 37,
156
+ 'dark_grey': 90,
157
+ 'light_red': 91,
158
+ 'light_green': 92,
159
+ 'light_yellow': 93,
160
+ 'light_blue': 94,
161
+ 'light_magenta': 95,
162
+ 'light_cyan': 96,
163
+ 'white': 97,
164
+ }
165
+
166
+
167
+ RESET = '\033[0m'
168
+
169
+
170
+ # pylint: disable-next=too-many-return-statements
171
+ def _can_do_color(
172
+ *,
173
+ no_color: bool | None = None,
174
+ force_color: bool | None = None,
175
+ ) -> bool:
176
+ """Check env vars and for tty/dumb terminal."""
177
+ # First check overrides:
178
+ # "User-level configuration files and per-instance command-line arguments should
179
+ # override $NO_COLOR. A user should be able to export $NO_COLOR in their shell
180
+ # configuration file as a default, but configure a specific program in its
181
+ # configuration file to specifically enable color."
182
+ # https://no-color.org
183
+ if no_color is not None and no_color:
184
+ return False
185
+ if force_color is not None and force_color:
186
+ return True
187
+
188
+ # Then check env vars:
189
+ if 'ANSI_COLORS_DISABLED' in os.environ:
190
+ return False
191
+ if 'NO_COLOR' in os.environ:
192
+ return False
193
+ if 'FORCE_COLOR' in os.environ:
194
+ return True
195
+
196
+ # Then check system:
197
+ if os.environ.get('TERM') == 'dumb':
198
+ return False
199
+ if not hasattr(sys.stdout, 'fileno'):
200
+ return False
201
+
202
+ try:
203
+ return os.isatty(sys.stdout.fileno())
204
+ except io.UnsupportedOperation:
205
+ return sys.stdout.isatty()
206
+
207
+
208
+ # pylint: disable-next=too-many-arguments
209
+ def colored(
210
+ text: Any,
211
+ /,
212
+ color: Color | None = None,
213
+ on_color: Highlight | None = None,
214
+ attrs: Iterable[Attribute] | None = None,
215
+ *,
216
+ no_color: bool | None = None,
217
+ force_color: bool | None = None,
218
+ ) -> str:
219
+ """Colorize text.
220
+
221
+ Available text colors:
222
+ black, red, green, yellow, blue, magenta, cyan, white,
223
+ light_grey, dark_grey, light_red, light_green, light_yellow, light_blue,
224
+ light_magenta, light_cyan.
225
+
226
+ Available text highlights:
227
+ on_black, on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white,
228
+ on_light_grey, on_dark_grey, on_light_red, on_light_green, on_light_yellow,
229
+ on_light_blue, on_light_magenta, on_light_cyan.
230
+
231
+ Available attributes:
232
+ bold, dark, underline, blink, reverse, concealed.
233
+
234
+ Example:
235
+ colored('Hello, World!', 'red', 'on_black', ['bold', 'blink'])
236
+ colored('Hello, World!', 'green')
237
+ """
238
+ result = str(text)
239
+ if not _can_do_color(no_color=no_color, force_color=force_color):
240
+ return result
241
+
242
+ fmt_str = '\033[%dm%s'
243
+ if color is not None:
244
+ result = fmt_str % (COLORS[color], result)
245
+
246
+ if on_color is not None:
247
+ result = fmt_str % (HIGHLIGHTS[on_color], result)
248
+
249
+ if attrs is not None:
250
+ for attr in attrs:
251
+ result = fmt_str % (ATTRIBUTES[attr], result)
252
+
253
+ result += RESET
254
+
255
+ return result
256
+
257
+
258
+ # pylint: disable-next=too-many-arguments
259
+ def cprint(
260
+ text: object,
261
+ /,
262
+ color: Color | None = None,
263
+ on_color: Highlight | None = None,
264
+ attrs: Iterable[Attribute] | None = None,
265
+ *,
266
+ no_color: bool | None = None,
267
+ force_color: bool | None = None,
268
+ **kwargs: Any,
269
+ ) -> None:
270
+ """Print colorized text.
271
+
272
+ It accepts arguments of print function.
273
+ """
274
+ print(
275
+ colored(
276
+ text,
277
+ color,
278
+ on_color,
279
+ attrs,
280
+ no_color=no_color,
281
+ force_color=force_color,
282
+ ),
283
+ **kwargs,
284
+ )
.venv/lib/python3.10/site-packages/nvitop/api/utils.py ADDED
@@ -0,0 +1,799 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is part of nvitop, the interactive NVIDIA-GPU process viewer.
2
+ #
3
+ # Copyright 2021-2025 Xuehai Pan. All Rights Reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ # ==============================================================================
17
+ """Utilities of nvitop APIs."""
18
+
19
+ # pylint: disable=invalid-name
20
+
21
+ from __future__ import annotations
22
+
23
+ import ctypes
24
+ import datetime
25
+ import functools
26
+ import math
27
+ import os
28
+ import re
29
+ import sys
30
+ import time
31
+ from collections.abc import KeysView
32
+ from typing import TYPE_CHECKING, Any, Callable, ClassVar, TypeVar, final
33
+
34
+ from nvitop.api import termcolor
35
+
36
+
37
+ if TYPE_CHECKING:
38
+ from collections.abc import Generator, Iterable, Iterator
39
+
40
+
41
+ __all__ = [ # noqa: RUF022
42
+ 'NA',
43
+ 'NaType',
44
+ 'NotApplicable',
45
+ 'NotApplicableType',
46
+ 'UINT_MAX',
47
+ 'ULONGLONG_MAX',
48
+ 'KiB',
49
+ 'MiB',
50
+ 'GiB',
51
+ 'TiB',
52
+ 'PiB',
53
+ 'SIZE_UNITS',
54
+ 'bytes2human',
55
+ 'human2bytes',
56
+ 'timedelta2human',
57
+ 'utilization2string',
58
+ 'colored',
59
+ 'set_color',
60
+ 'boolify',
61
+ 'Snapshot',
62
+ ]
63
+
64
+
65
+ COLOR: bool = sys.stdout.isatty()
66
+
67
+
68
+ def set_color(value: bool) -> None:
69
+ """Force enable text coloring."""
70
+ global COLOR # pylint: disable=global-statement
71
+ COLOR = bool(value)
72
+ if COLOR:
73
+ os.environ['FORCE_COLOR'] = '1'
74
+ os.environ.pop('NO_COLOR', None)
75
+ else:
76
+ os.environ.pop('FORCE_COLOR', None)
77
+ os.environ['NO_COLOR'] = '1'
78
+
79
+
80
+ def colored(
81
+ text: Any,
82
+ /,
83
+ color: termcolor.Color | None = None,
84
+ on_color: termcolor.Highlight | None = None,
85
+ attrs: Iterable[termcolor.Attribute] | None = None,
86
+ ) -> str:
87
+ """Colorize text with ANSI color escape codes.
88
+
89
+ Available text colors:
90
+ red, green, yellow, blue, magenta, cyan, white.
91
+
92
+ Available text highlights:
93
+ on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white.
94
+
95
+ Available attributes:
96
+ bold, dark, underline, blink, reverse, concealed.
97
+
98
+ Examples:
99
+ >>> colored('Hello, World!', 'red', 'on_grey', ['bold', 'blink']) # doctest: +ELLIPSIS
100
+ '...Hello, World!...'
101
+ >>> colored('Hello, World!', 'green') # doctest: +ELLIPSIS
102
+ '...Hello, World!...'
103
+ """
104
+ if COLOR:
105
+ return termcolor.colored(text, color=color, on_color=on_color, attrs=attrs)
106
+ return str(text)
107
+
108
+
109
+ @final
110
+ class NaType(str):
111
+ """A singleton (:const:`str: 'N/A'`) class represents a not applicable value.
112
+
113
+ The :const:`NA` instance behaves like a :class:`str` instance (:const:`'N/A'`) when doing string
114
+ manipulation (e.g. concatenation). For arithmetic operations, for example ``NA / 1024 / 1024``,
115
+ it acts like the :data:`math.nan`.
116
+
117
+ Examples:
118
+ >>> NA
119
+ 'N/A'
120
+
121
+ >>> 'memory usage: {}'.format(NA) # NA is an instance of `str`
122
+ 'memory usage: N/A'
123
+ >>> NA.lower() # NA is an instance of `str`
124
+ 'n/a'
125
+ >>> NA.ljust(5) # NA is an instance of `str`
126
+ 'N/A '
127
+ >>> NA + ' str' # string contamination if the operand is a string
128
+ 'N/A str'
129
+
130
+ >>> float(NA) # explicit conversion to float (`math.nan`)
131
+ nan
132
+ >>> NA + 1 # auto-casting to float if the operand is a number
133
+ nan
134
+ >>> NA * 1024 # auto-casting to float if the operand is a number
135
+ nan
136
+ >>> NA / (1024 * 1024) # auto-casting to float if the operand is a number
137
+ nan
138
+ """
139
+
140
+ __slots__: ClassVar[tuple[()]] = ()
141
+
142
+ def __new__(cls) -> NaType:
143
+ """Get the singleton instance (:const:`nvitop.NA`)."""
144
+ instance = getattr(cls, '_instance', None)
145
+ if instance is None:
146
+ cls._instance = instance = super().__new__(cls, 'N/A')
147
+ return instance
148
+
149
+ def __bool__(self) -> bool:
150
+ """Convert :const:`NA` to :class:`bool` and return :data:`False`.
151
+
152
+ >>> bool(NA)
153
+ False
154
+ """
155
+ return False
156
+
157
+ def __int__(self) -> int:
158
+ """Convert :const:`NA` to :class:`int` and return :const:`0`.
159
+
160
+ >>> int(NA)
161
+ 0
162
+ """
163
+ return 0
164
+
165
+ def __float__(self) -> float:
166
+ """Convert :const:`NA` to :class:`float` and return :data:`math.nan`.
167
+
168
+ >>> float(NA)
169
+ nan
170
+ >>> float(NA) is math.nan
171
+ True
172
+ """
173
+ return math.nan
174
+
175
+ def __add__(self, other: object) -> str | float: # type: ignore[override]
176
+ """Return :data:`math.nan` if the operand is a number or uses string concatenation if the operand is a string (``NA + other``).
177
+
178
+ A special case is when the operand is :const:`nvitop.NA` itself, the result is
179
+ :data:`math.nan` instead of :const:`'N/AN/A'`.
180
+
181
+ >>> NA + ' str'
182
+ 'N/A str'
183
+ >>> NA + NA
184
+ nan
185
+ >>> NA + 1
186
+ nan
187
+ >>> NA + 1.0
188
+ nan
189
+ """ # pylint: disable=line-too-long
190
+ if isinstance(other, (int, float)):
191
+ return float(self) + other
192
+ if other is NA:
193
+ return float(self)
194
+ return super().__add__(other) # type: ignore[operator]
195
+
196
+ def __radd__(self, other: object) -> str | float:
197
+ """Return :data:`math.nan` if the operand is a number or uses string concatenation if the operand is a string (``other + NA``).
198
+
199
+ >>> 'str' + NA
200
+ 'strN/A'
201
+ >>> 1 + NA
202
+ nan
203
+ >>> 1.0 + NA
204
+ nan
205
+ """ # pylint: disable=line-too-long
206
+ if isinstance(other, (int, float)):
207
+ return other + float(self)
208
+ return NotImplemented
209
+
210
+ def __sub__(self, other: object) -> float:
211
+ """Return :data:`math.nan` if the operand is a number (``NA - other``).
212
+
213
+ >>> NA - 'str'
214
+ Traceback (most recent call last):
215
+ ...
216
+ TypeError: unsupported operand type(s) for -: 'NaType' and 'str'
217
+ >>> NA - NA
218
+ nan
219
+ >>> NA + 1
220
+ nan
221
+ >>> NA + 1.0
222
+ nan
223
+ """
224
+ if isinstance(other, (int, float)):
225
+ return float(self) - other
226
+ if other is NA:
227
+ return float(self)
228
+ return NotImplemented
229
+
230
+ def __rsub__(self, other: object) -> float:
231
+ """Return :data:`math.nan` if the operand is a number (``other - NA``).
232
+
233
+ >>> 'str' - NA
234
+ Traceback (most recent call last):
235
+ ...
236
+ TypeError: unsupported operand type(s) for -: 'str' and 'NaType'
237
+ >>> 1 - NA
238
+ nan
239
+ >>> 1.0 - NA
240
+ nan
241
+ """
242
+ if isinstance(other, (int, float)):
243
+ return other - float(self)
244
+ return NotImplemented
245
+
246
+ def __mul__(self, other: object) -> float: # type: ignore[override]
247
+ """Return :data:`math.nan` if the operand is a number (``NA * other``).
248
+
249
+ A special case is when the operand is :const:`nvitop.NA` itself, the result is also :data:`math.nan`.
250
+
251
+ >>> NA * 1024
252
+ nan
253
+ >>> NA * 1024.0
254
+ nan
255
+ >>> NA * NA
256
+ nan
257
+ """
258
+ if isinstance(other, (int, float)):
259
+ return float(self) * other
260
+ if other is NA:
261
+ return float(self)
262
+ return NotImplemented
263
+
264
+ def __rmul__(self, other: object) -> float: # type: ignore[override]
265
+ """Return :data:`math.nan` if the operand is a number (``other * NA``).
266
+
267
+ >>> 1024 * NA
268
+ nan
269
+ >>> 1024.0 * NA
270
+ nan
271
+ """
272
+ if isinstance(other, (int, float)):
273
+ return other * float(self)
274
+ return NotImplemented
275
+
276
+ def __truediv__(self, other: object) -> float:
277
+ """Return :data:`math.nan` if the operand is a number (``NA / other``).
278
+
279
+ >>> NA / 1024
280
+ nan
281
+ >>> NA / 1024.0
282
+ nan
283
+ >>> NA / 0
284
+ Traceback (most recent call last):
285
+ ...
286
+ ZeroDivisionError: ...
287
+ >>> NA / 0.0
288
+ Traceback (most recent call last):
289
+ ...
290
+ ZeroDivisionError: ...
291
+ >>> NA / NA
292
+ nan
293
+ """
294
+ if isinstance(other, (int, float)):
295
+ return float(self) / other
296
+ if other is NA:
297
+ return float(self)
298
+ return NotImplemented
299
+
300
+ def __rtruediv__(self, other: object) -> float:
301
+ """Return :data:`math.nan` if the operand is a number (``other / NA``).
302
+
303
+ >>> 1024 / NA
304
+ nan
305
+ >>> 1024.0 / NA
306
+ nan
307
+ """
308
+ if isinstance(other, (int, float)):
309
+ return other / float(self)
310
+ return NotImplemented
311
+
312
+ def __floordiv__(self, other: object) -> float:
313
+ """Return :data:`math.nan` if the operand is a number (``NA // other``).
314
+
315
+ >>> NA // 1024
316
+ nan
317
+ >>> NA // 1024.0
318
+ nan
319
+ >>> NA / 0
320
+ Traceback (most recent call last):
321
+ ...
322
+ ZeroDivisionError: ...
323
+ >>> NA / 0.0
324
+ Traceback (most recent call last):
325
+ ...
326
+ ZeroDivisionError: ...
327
+ >>> NA // NA
328
+ nan
329
+ """
330
+ if isinstance(other, (int, float)):
331
+ return float(self) // other
332
+ if other is NA:
333
+ return float(self)
334
+ return NotImplemented
335
+
336
+ def __rfloordiv__(self, other: object) -> float:
337
+ """Return :data:`math.nan` if the operand is a number (``other // NA``).
338
+
339
+ >>> 1024 // NA
340
+ nan
341
+ >>> 1024.0 // NA
342
+ nan
343
+ """
344
+ if isinstance(other, (int, float)):
345
+ return other // float(self)
346
+ return NotImplemented
347
+
348
+ def __mod__(self, other: object) -> float: # type: ignore[override]
349
+ """Return :data:`math.nan` if the operand is a number (``NA % other``).
350
+
351
+ >>> NA % 1024
352
+ nan
353
+ >>> NA % 1024.0
354
+ nan
355
+ >>> NA % 0
356
+ Traceback (most recent call last):
357
+ ...
358
+ ZeroDivisionError: ...
359
+ >>> NA % 0.0
360
+ Traceback (most recent call last):
361
+ ...
362
+ ZeroDivisionError: ...
363
+ """
364
+ if isinstance(other, (int, float)):
365
+ return float(self) % other
366
+ if other is NA:
367
+ return float(self)
368
+ return NotImplemented
369
+
370
+ def __rmod__(self, other: object) -> float:
371
+ """Return :data:`math.nan` if the operand is a number (``other % NA``).
372
+
373
+ >>> 1024 % NA
374
+ nan
375
+ >>> 1024.0 % NA
376
+ nan
377
+ """
378
+ if isinstance(other, (int, float)):
379
+ return other % float(self)
380
+ return NotImplemented
381
+
382
+ def __divmod__(self, other: object) -> tuple[float, float]:
383
+ """The pair ``(NA // other, NA % other)`` (``divmod(NA, other)``).
384
+
385
+ >>> divmod(NA, 1024)
386
+ (nan, nan)
387
+ >>> divmod(NA, 1024.0)
388
+ (nan, nan)
389
+ >>> divmod(NA, 0)
390
+ Traceback (most recent call last):
391
+ ...
392
+ ZeroDivisionError: ...
393
+ >>> divmod(NA, 0.0)
394
+ Traceback (most recent call last):
395
+ ...
396
+ ZeroDivisionError: ...
397
+ """
398
+ return (self // other, self % other)
399
+
400
+ def __rdivmod__(self, other: object) -> tuple[float, float]:
401
+ """The pair ``(other // NA, other % NA)`` (``divmod(other, NA)``).
402
+
403
+ >>> divmod(1024, NA)
404
+ (nan, nan)
405
+ >>> divmod(1024.0, NA)
406
+ (nan, nan)
407
+ """
408
+ return (other // self, other % self)
409
+
410
+ def __pos__(self) -> float:
411
+ """Return :data:`math.nan` (``+NA``).
412
+
413
+ >>> +NA
414
+ nan
415
+ """
416
+ return +float(self)
417
+
418
+ def __neg__(self) -> float:
419
+ """Return :data:`math.nan` (``-NA``).
420
+
421
+ >>> -NA
422
+ nan
423
+ """
424
+ return -float(self)
425
+
426
+ def __abs__(self) -> float:
427
+ """Return :data:`math.nan` (``abs(NA)``).
428
+
429
+ >>> abs(NA)
430
+ nan
431
+ """
432
+ return abs(float(self))
433
+
434
+ def __round__(self, ndigits: int | None = None) -> int | float:
435
+ """Round :const:`nvitop.NA` to ``ndigits`` decimal places, defaulting to :data:`None`.
436
+
437
+ If ``ndigits`` is omitted or :data:`None`, returns :const:`0`, otherwise returns :data:`math.nan`.
438
+
439
+ >>> round(NA)
440
+ 0
441
+ >>> round(NA, 0)
442
+ nan
443
+ >>> round(NA, 1)
444
+ nan
445
+ """
446
+ if ndigits is None:
447
+ return int(self)
448
+ return round(float(self), ndigits)
449
+
450
+ def __lt__(self, x: object) -> bool:
451
+ """The :const:`nvitop.NA` is always greater than any number, or uses the dictionary order for string."""
452
+ if isinstance(x, (int, float)):
453
+ return False
454
+ return super().__lt__(x) # type: ignore[operator]
455
+
456
+ def __le__(self, x: object) -> bool:
457
+ """The :const:`nvitop.NA` is always greater than any number, or uses the dictionary order for string."""
458
+ if isinstance(x, (int, float)):
459
+ return False
460
+ return super().__le__(x) # type: ignore[operator]
461
+
462
+ def __gt__(self, x: object) -> bool:
463
+ """The :const:`nvitop.NA` is always greater than any number, or uses the dictionary order for string."""
464
+ if isinstance(x, (int, float)):
465
+ return True
466
+ return super().__gt__(x) # type: ignore[operator]
467
+
468
+ def __ge__(self, x: object) -> bool:
469
+ """The :const:`nvitop.NA` is always greater than any number, or uses the dictionary order for string."""
470
+ if isinstance(x, (int, float)):
471
+ return True
472
+ return super().__ge__(x) # type: ignore[operator]
473
+
474
+ def __format__(self, format_spec: str) -> str:
475
+ """Format :const:`nvitop.NA` according to ``format_spec``."""
476
+ try:
477
+ return super().__format__(format_spec)
478
+ except ValueError:
479
+ return format(math.nan, format_spec)
480
+
481
+
482
+ NotApplicableType = NaType
483
+
484
+ # isinstance(NA, str) -> True
485
+ # NA == 'N/A' -> True
486
+ # NA is NaType() -> True (`NaType` is a singleton class)
487
+ NA = NaType()
488
+ """The singleton instance of :class:`NaType`. The actual value is :const:`str: 'N/A'`."""
489
+
490
+ NotApplicable = NA
491
+ """The singleton instance of :class:`NaType`. The actual value is :const:`str: 'N/A'`."""
492
+
493
+ UINT_MAX: int = ctypes.c_uint(-1).value # 0xFFFFFFFF
494
+ """The maximum value of :class:`ctypes.c_uint`."""
495
+ ULONGLONG_MAX: int = ctypes.c_ulonglong(-1).value # 0XFFFFFFFFFFFFFFFF
496
+ """The maximum value of :class:`ctypes.c_ulonglong`."""
497
+
498
+ KiB: int = 1 << 10
499
+ """Kibibyte (1024)"""
500
+
501
+ MiB: int = 1 << 20
502
+ """Mebibyte (1024 * 1024)"""
503
+
504
+ GiB: int = 1 << 30
505
+ """Gibibyte (1024 * 1024 * 1024)"""
506
+
507
+ TiB: int = 1 << 40
508
+ """Tebibyte (1024 * 1024 * 1024 * 1024)"""
509
+
510
+ PiB: int = 1 << 50
511
+ """Pebibyte (1024 * 1024 * 1024 * 1024 * 1024)"""
512
+
513
+ SIZE_UNITS: dict[str | None, int] = {
514
+ None: 1,
515
+ '': 1,
516
+ 'B': 1,
517
+ 'KiB': KiB,
518
+ 'MiB': MiB,
519
+ 'GiB': GiB,
520
+ 'TiB': TiB,
521
+ 'PiB': PiB,
522
+ 'KB': 1000,
523
+ 'MB': 1000**2,
524
+ 'GB': 1000**3,
525
+ 'TB': 1000**4,
526
+ 'PB': 1000**5,
527
+ }
528
+ """Units of storage and memory measurements."""
529
+ SIZE_PATTERN: re.Pattern = re.compile(
530
+ r'^\s*\+?\s*(?P<size>\d+(?:\.\d+)?)\s*(?P<unit>([KMGTP]i?)?)B?\s*$',
531
+ flags=re.IGNORECASE,
532
+ )
533
+ """The regex pattern for human readable size."""
534
+
535
+
536
+ # pylint: disable-next=too-many-return-statements,too-many-branches
537
+ def bytes2human(
538
+ b: int | float | NaType, # noqa: PYI041
539
+ /,
540
+ *,
541
+ min_unit: int = 1,
542
+ ) -> str:
543
+ """Convert bytes to a human readable string."""
544
+ if b == NA:
545
+ return NA
546
+
547
+ if not isinstance(b, int):
548
+ try:
549
+ b = round(float(b))
550
+ except ValueError:
551
+ return NA
552
+
553
+ if b < KiB and min_unit < KiB:
554
+ return f'{b}B'
555
+ if b < MiB and min_unit <= KiB:
556
+ return f'{round(b / KiB)}KiB'
557
+ if b < 100 * MiB and min_unit <= MiB:
558
+ return f'{round(b / MiB, 2):.2f}MiB'
559
+ if b < 1000 * MiB and min_unit <= MiB:
560
+ return f'{round(b / MiB, 1):.1f}MiB'
561
+ if b < 20 * GiB and min_unit <= MiB:
562
+ return f'{round(b / MiB)}MiB'
563
+ if b < 100 * GiB and min_unit <= GiB:
564
+ return f'{round(b / GiB, 2):.2f}GiB'
565
+ if b < 1000 * GiB and min_unit <= GiB:
566
+ return f'{round(b / GiB, 1):.1f}GiB'
567
+ if b < 100 * TiB and min_unit <= TiB:
568
+ return f'{round(b / TiB, 2):.2f}TiB'
569
+ if b < 1000 * TiB and min_unit <= TiB:
570
+ return f'{round(b / TiB, 1):.1f}TiB'
571
+ if b < 100 * PiB:
572
+ return f'{round(b / PiB, 2):.2f}PiB'
573
+ return f'{round(b / PiB, 1):.1f}PiB'
574
+
575
+
576
+ def human2bytes(s: int | str, /) -> int:
577
+ """Convert a human readable size string (*case insensitive*) to bytes.
578
+
579
+ Raises:
580
+ ValueError:
581
+ If cannot convert the given size string.
582
+
583
+ Examples:
584
+ >>> human2bytes('200')
585
+ 200
586
+ >>> human2bytes('500B')
587
+ 500
588
+ >>> human2bytes('10k')
589
+ 10000
590
+ >>> human2bytes('10ki')
591
+ 10240
592
+ >>> human2bytes('1M')
593
+ 1000000
594
+ >>> human2bytes('1MiB')
595
+ 1048576
596
+ >>> human2bytes('1.5GiB')
597
+ 1610612736
598
+ """
599
+ if isinstance(s, int):
600
+ if s >= 0:
601
+ return s
602
+ raise ValueError(f'Cannot convert {s!r} to bytes.')
603
+
604
+ match = SIZE_PATTERN.fullmatch(s)
605
+ if match is None:
606
+ raise ValueError(f'Cannot convert {s!r} to bytes.')
607
+ size, unit = match.group('size', 'unit')
608
+ unit = unit.upper().replace('I', 'i')
609
+ return int(float(size) * SIZE_UNITS[f'{unit}B'])
610
+
611
+
612
+ def timedelta2human(
613
+ dt: int | float | datetime.timedelta | NaType, # noqa: PYI041
614
+ /,
615
+ *,
616
+ round: bool = False, # pylint: disable=redefined-builtin
617
+ ) -> str:
618
+ """Convert a number in seconds or a :class:`datetime.timedelta` instance to a human readable string."""
619
+ if isinstance(dt, (int, float)):
620
+ dt = datetime.timedelta(seconds=dt)
621
+
622
+ if not isinstance(dt, datetime.timedelta):
623
+ return NA
624
+
625
+ if dt.days >= 4 or (round and dt.days >= 1):
626
+ return f'{dt.days + dt.seconds / 86400:.1f} days'
627
+
628
+ hours, seconds = divmod(86400 * dt.days + dt.seconds, 3600)
629
+ if hours > 0:
630
+ return '{:d}:{:02d}:{:02d}'.format(hours, *divmod(seconds, 60))
631
+ return '{:d}:{:02d}'.format(*divmod(seconds, 60))
632
+
633
+
634
+ def utilization2string(utilization: int | float | NaType, /) -> str: # noqa: PYI041
635
+ """Convert a utilization rate to string."""
636
+ if utilization != NA:
637
+ if isinstance(utilization, int):
638
+ return f'{utilization}%'
639
+ if isinstance(utilization, float):
640
+ return f'{utilization:.1f}%'
641
+ return NA
642
+
643
+
644
+ def boolify(string: str, /, default: Any = None) -> bool:
645
+ """Convert the given value, usually a string, to boolean."""
646
+ if string.lower() in {'true', 'yes', 'on', 'enabled', '1'}:
647
+ return True
648
+ if string.lower() in {'false', 'no', 'off', 'disabled', '0'}:
649
+ return False
650
+ if default is not None:
651
+ return bool(default)
652
+ return bool(string)
653
+
654
+
655
+ class Snapshot:
656
+ """A dict-like object holds the snapshot values.
657
+
658
+ The value can be accessed by ``snapshot.name`` or ``snapshot['name']`` syntax.
659
+ The Snapshot can also be converted to a dictionary by ``dict(snapshot)`` or ``{**snapshot}``.
660
+
661
+ Missing attributes will be automatically fetched from the original object.
662
+ """
663
+
664
+ def __init__(self, real: Any, **items: Any) -> None:
665
+ """Initialize a new :class:`Snapshot` object with the given attributes."""
666
+ object.__setattr__(self, 'real', real)
667
+ object.__setattr__(self, 'timestamp', time.time())
668
+ for key, value in items.items():
669
+ setattr(self, key, value)
670
+
671
+ def __repr__(self) -> str:
672
+ """Return a string representation of the snapshot."""
673
+ keys = set(self.__dict__.keys()).difference({'real', 'timestamp'})
674
+ keys = ['real', *sorted(keys)]
675
+ keyvals = []
676
+ for key in keys:
677
+ value = getattr(self, key)
678
+ keyval = f'{key}={value!r}'
679
+ if isinstance(value, Snapshot):
680
+ keyval = keyval.replace('\n', '\n ') # extra indentation for nested snapshots
681
+ keyvals.append(keyval)
682
+ return '{}{}(\n {},\n)'.format(
683
+ self.real.__class__.__name__,
684
+ self.__class__.__name__,
685
+ ',\n '.join(keyvals),
686
+ )
687
+
688
+ def __hash__(self) -> int:
689
+ """Return a hash value of the snapshot."""
690
+ return hash((self.real, self.timestamp))
691
+
692
+ def __getattr__(self, name: str) -> Any:
693
+ """Get a member from the instance.
694
+
695
+ If the attribute is not defined, fetches from the original object and makes a function call.
696
+ """
697
+ try:
698
+ return super().__getattr__(name) # type: ignore[misc]
699
+ except AttributeError:
700
+ attribute = getattr(self.real, name)
701
+ if callable(attribute):
702
+ attribute = attribute()
703
+
704
+ setattr(self, name, attribute)
705
+ return attribute
706
+
707
+ def __getitem__(self, name: str) -> Any:
708
+ """Support ``snapshot['name']`` syntax."""
709
+ try:
710
+ return getattr(self, name)
711
+ except AttributeError as ex:
712
+ raise KeyError(name) from ex
713
+
714
+ def __setitem__(self, name: str, value: Any) -> None:
715
+ """Support ``snapshot['name'] = value`` syntax."""
716
+ setattr(self, name, value)
717
+
718
+ def __setattr__(self, name: str, value: Any) -> None:
719
+ """Set or update a member of the instance.
720
+
721
+ If the attribute is not defined, set it to the snapshot object.
722
+ """
723
+ if name in ('real', 'timestamp'):
724
+ raise AttributeError(f'Cannot set attribute {name!r} of {self.__class__.__name__!r}')
725
+ super().__setattr__(name, value)
726
+
727
+ def __iter__(self) -> Iterator[str]:
728
+ """Support ``for name in snapshot`` syntax and ``*`` tuple unpack ``[*snapshot]`` syntax."""
729
+
730
+ def gen() -> Generator[str]:
731
+ yield from (name for name in self.__dict__ if name not in {'real', 'timestamp'})
732
+
733
+ return gen()
734
+
735
+ def keys(self) -> Iterable[str]:
736
+ # pylint: disable-next=line-too-long
737
+ """Support ``**`` dictionary unpack ``{**snapshot}`` / ``dict(**snapshot)`` syntax and ``dict(snapshot)`` dictionary conversion."""
738
+ return KeysView(self) # type: ignore[arg-type]
739
+
740
+
741
+ Method = TypeVar('Method', bound=Callable[..., Any])
742
+
743
+
744
+ # Modified from psutil (https://github.com/giampaolo/psutil)
745
+ def memoize_when_activated(method: Method, /) -> Method:
746
+ """A memoize decorator which is disabled by default.
747
+
748
+ It can be activated and deactivated on request. For efficiency reasons it can be used only
749
+ against class methods accepting no arguments.
750
+ """
751
+
752
+ @functools.wraps(method)
753
+ def wrapped(self: object, /, *args: Any, **kwargs: Any) -> Any:
754
+ try:
755
+ # case 1: we previously entered oneshot() ctx
756
+ # pylint: disable-next=protected-access
757
+ ret = self._cache[method] # type: ignore[attr-defined]
758
+ except AttributeError:
759
+ # case 2: we never entered oneshot() ctx
760
+ return method(self, *args, **kwargs)
761
+ except KeyError:
762
+ # case 3: we entered oneshot() ctx but there's no cache
763
+ # for this entry yet
764
+ ret = method(self, *args, **kwargs)
765
+ try:
766
+ # pylint: disable-next=protected-access
767
+ self._cache[method] = ret # type: ignore[attr-defined]
768
+ except AttributeError:
769
+ # multi-threading race condition, see:
770
+ # https://github.com/giampaolo/psutil/issues/1948
771
+ pass
772
+ return ret
773
+
774
+ def cache_activate(self: object) -> None:
775
+ """Activate cache.
776
+
777
+ Expects an instance. Cache will be stored as a "_cache" instance attribute.
778
+ """
779
+ if not hasattr(self, '_cache'):
780
+ # pylint: disable-next=protected-access
781
+ self._cache = {} # type: ignore[attr-defined]
782
+
783
+ def cache_deactivate(self: object) -> None:
784
+ """Deactivate and clear cache."""
785
+ try:
786
+ # pylint: disable-next=protected-access
787
+ del self._cache # type: ignore[attr-defined]
788
+ except AttributeError:
789
+ pass
790
+
791
+ wrapped.cache_activate = cache_activate # type: ignore[attr-defined]
792
+ wrapped.cache_deactivate = cache_deactivate # type: ignore[attr-defined]
793
+ return wrapped # type: ignore[return-value]
794
+
795
+
796
+ if __name__ == '__main__':
797
+ import doctest
798
+
799
+ doctest.testmod()