ZTWHHH commited on
Commit
ed6868e
·
verified ·
1 Parent(s): 8160de7

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. parrot/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/common_tests.cpython-310.pyc +0 -0
  2. parrot/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_censored_data.cpython-310.pyc +0 -0
  3. parrot/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_discrete_distns.cpython-310.pyc +0 -0
  4. parrot/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_kdeoth.cpython-310.pyc +0 -0
  5. parrot/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_mgc.cpython-310.pyc +0 -0
  6. parrot/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_relative_risk.cpython-310.pyc +0 -0
  7. parrot/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_sensitivity_analysis.cpython-310.pyc +0 -0
  8. parrot/lib/python3.10/site-packages/scipy/stats/tests/test_qmc.py +1410 -0
  9. parrot/lib/python3.10/site-packages/scipy/stats/tests/test_stats.py +0 -0
  10. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_cast_Short_ops.h +28 -0
  11. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_cufft_clear_plan_cache_native.h +21 -0
  12. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_tensor_storage_offsets_ops.h +39 -0
  13. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_to_sparse_csr_cuda_dispatch.h +23 -0
  14. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/bernoulli_ops.h +105 -0
  15. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/convolution_backward_overrideable.h +91 -0
  16. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/fused_moving_avg_obs_fake_quant_ops.h +28 -0
  17. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/hann_window.h +61 -0
  18. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/is_signed.h +30 -0
  19. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/leaky_relu_backward.h +39 -0
  20. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/rnn_relu_compositeimplicitautograd_dispatch.h +24 -0
  21. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/select_scatter_native.h +22 -0
  22. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/sym_storage_offset_compositeimplicitautograd_dispatch.h +23 -0
  23. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/trapz.h +35 -0
  24. vllm/lib/python3.10/site-packages/ray/cloudpickle/__pycache__/__init__.cpython-310.pyc +0 -0
  25. vllm/lib/python3.10/site-packages/ray/cloudpickle/__pycache__/cloudpickle.cpython-310.pyc +0 -0
  26. vllm/lib/python3.10/site-packages/ray/cloudpickle/__pycache__/compat.cpython-310.pyc +0 -0
  27. vllm/lib/python3.10/site-packages/ray/cloudpickle/py_pickle.py +30 -0
  28. vllm/lib/python3.10/site-packages/ray/internal/__init__.py +3 -0
  29. vllm/lib/python3.10/site-packages/ray/internal/__pycache__/__init__.cpython-310.pyc +0 -0
  30. vllm/lib/python3.10/site-packages/ray/scripts/__init__.py +0 -0
  31. vllm/lib/python3.10/site-packages/ray/scripts/__pycache__/__init__.cpython-310.pyc +0 -0
  32. vllm/lib/python3.10/site-packages/ray/scripts/__pycache__/scripts.cpython-310.pyc +0 -0
  33. vllm/lib/python3.10/site-packages/ray/scripts/scripts.py +2672 -0
  34. vllm/lib/python3.10/site-packages/ray/train/__init__.py +65 -0
  35. vllm/lib/python3.10/site-packages/ray/train/_checkpoint.py +424 -0
  36. vllm/lib/python3.10/site-packages/ray/train/backend.py +59 -0
  37. vllm/lib/python3.10/site-packages/ray/train/constants.py +105 -0
  38. vllm/lib/python3.10/site-packages/ray/train/context.py +92 -0
  39. vllm/lib/python3.10/site-packages/ray/train/data_parallel_trainer.py +587 -0
  40. vllm/lib/python3.10/site-packages/ray/train/error.py +6 -0
  41. vllm/lib/python3.10/site-packages/ray/train/examples/__init__.py +0 -0
  42. vllm/lib/python3.10/site-packages/ray/train/examples/horovod/__init__.py +0 -0
  43. vllm/lib/python3.10/site-packages/ray/train/examples/horovod/__pycache__/__init__.cpython-310.pyc +0 -0
  44. vllm/lib/python3.10/site-packages/ray/train/examples/horovod/__pycache__/horovod_cifar_pbt_example.cpython-310.pyc +0 -0
  45. vllm/lib/python3.10/site-packages/ray/train/examples/horovod/__pycache__/horovod_example.cpython-310.pyc +0 -0
  46. vllm/lib/python3.10/site-packages/ray/train/examples/horovod/__pycache__/horovod_pytorch_example.cpython-310.pyc +0 -0
  47. vllm/lib/python3.10/site-packages/ray/train/examples/horovod/__pycache__/horovod_tune_example.cpython-310.pyc +0 -0
  48. vllm/lib/python3.10/site-packages/ray/train/examples/horovod/horovod_cifar_pbt_example.py +210 -0
  49. vllm/lib/python3.10/site-packages/ray/train/examples/horovod/horovod_example.py +286 -0
  50. vllm/lib/python3.10/site-packages/ray/train/examples/horovod/horovod_pytorch_example.py +270 -0
parrot/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/common_tests.cpython-310.pyc ADDED
Binary file (11.3 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_censored_data.cpython-310.pyc ADDED
Binary file (6.1 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_discrete_distns.cpython-310.pyc ADDED
Binary file (19.2 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_kdeoth.cpython-310.pyc ADDED
Binary file (16.5 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_mgc.cpython-310.pyc ADDED
Binary file (6.72 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_relative_risk.cpython-310.pyc ADDED
Binary file (3.21 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_sensitivity_analysis.cpython-310.pyc ADDED
Binary file (8.37 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/tests/test_qmc.py ADDED
@@ -0,0 +1,1410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from collections import Counter
3
+ from itertools import combinations, product
4
+
5
+ import pytest
6
+ import numpy as np
7
+ from numpy.testing import assert_allclose, assert_equal, assert_array_equal
8
+
9
+ from scipy.spatial import distance
10
+ from scipy.stats import shapiro
11
+ from scipy.stats._sobol import _test_find_index
12
+ from scipy.stats import qmc
13
+ from scipy.stats._qmc import (
14
+ van_der_corput, n_primes, primes_from_2_to,
15
+ update_discrepancy, QMCEngine, _l1_norm,
16
+ _perturb_discrepancy, _lloyd_centroidal_voronoi_tessellation
17
+ )
18
+
19
+
20
+ class TestUtils:
21
+ def test_scale(self):
22
+ # 1d scalar
23
+ space = [[0], [1], [0.5]]
24
+ out = [[-2], [6], [2]]
25
+ scaled_space = qmc.scale(space, l_bounds=-2, u_bounds=6)
26
+
27
+ assert_allclose(scaled_space, out)
28
+
29
+ # 2d space
30
+ space = [[0, 0], [1, 1], [0.5, 0.5]]
31
+ bounds = np.array([[-2, 0], [6, 5]])
32
+ out = [[-2, 0], [6, 5], [2, 2.5]]
33
+
34
+ scaled_space = qmc.scale(space, l_bounds=bounds[0], u_bounds=bounds[1])
35
+
36
+ assert_allclose(scaled_space, out)
37
+
38
+ scaled_back_space = qmc.scale(scaled_space, l_bounds=bounds[0],
39
+ u_bounds=bounds[1], reverse=True)
40
+ assert_allclose(scaled_back_space, space)
41
+
42
+ # broadcast
43
+ space = [[0, 0, 0], [1, 1, 1], [0.5, 0.5, 0.5]]
44
+ l_bounds, u_bounds = 0, [6, 5, 3]
45
+ out = [[0, 0, 0], [6, 5, 3], [3, 2.5, 1.5]]
46
+
47
+ scaled_space = qmc.scale(space, l_bounds=l_bounds, u_bounds=u_bounds)
48
+
49
+ assert_allclose(scaled_space, out)
50
+
51
+ def test_scale_random(self):
52
+ rng = np.random.default_rng(317589836511269190194010915937762468165)
53
+ sample = rng.random((30, 10))
54
+ a = -rng.random(10) * 10
55
+ b = rng.random(10) * 10
56
+ scaled = qmc.scale(sample, a, b, reverse=False)
57
+ unscaled = qmc.scale(scaled, a, b, reverse=True)
58
+ assert_allclose(unscaled, sample)
59
+
60
+ def test_scale_errors(self):
61
+ with pytest.raises(ValueError, match=r"Sample is not a 2D array"):
62
+ space = [0, 1, 0.5]
63
+ qmc.scale(space, l_bounds=-2, u_bounds=6)
64
+
65
+ with pytest.raises(ValueError, match=r"Bounds are not consistent"):
66
+ space = [[0, 0], [1, 1], [0.5, 0.5]]
67
+ bounds = np.array([[-2, 6], [6, 5]])
68
+ qmc.scale(space, l_bounds=bounds[0], u_bounds=bounds[1])
69
+
70
+ with pytest.raises(ValueError, match=r"'l_bounds' and 'u_bounds'"
71
+ r" must be broadcastable"):
72
+ space = [[0, 0], [1, 1], [0.5, 0.5]]
73
+ l_bounds, u_bounds = [-2, 0, 2], [6, 5]
74
+ qmc.scale(space, l_bounds=l_bounds, u_bounds=u_bounds)
75
+
76
+ with pytest.raises(ValueError, match=r"'l_bounds' and 'u_bounds'"
77
+ r" must be broadcastable"):
78
+ space = [[0, 0], [1, 1], [0.5, 0.5]]
79
+ bounds = np.array([[-2, 0, 2], [6, 5, 5]])
80
+ qmc.scale(space, l_bounds=bounds[0], u_bounds=bounds[1])
81
+
82
+ with pytest.raises(ValueError, match=r"Sample is not in unit "
83
+ r"hypercube"):
84
+ space = [[0, 0], [1, 1.5], [0.5, 0.5]]
85
+ bounds = np.array([[-2, 0], [6, 5]])
86
+ qmc.scale(space, l_bounds=bounds[0], u_bounds=bounds[1])
87
+
88
+ with pytest.raises(ValueError, match=r"Sample is out of bounds"):
89
+ out = [[-2, 0], [6, 5], [8, 2.5]]
90
+ bounds = np.array([[-2, 0], [6, 5]])
91
+ qmc.scale(out, l_bounds=bounds[0], u_bounds=bounds[1],
92
+ reverse=True)
93
+
94
+ def test_discrepancy(self):
95
+ space_1 = np.array([[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]])
96
+ space_1 = (2.0 * space_1 - 1.0) / (2.0 * 6.0)
97
+ space_2 = np.array([[1, 5], [2, 4], [3, 3], [4, 2], [5, 1], [6, 6]])
98
+ space_2 = (2.0 * space_2 - 1.0) / (2.0 * 6.0)
99
+
100
+ # From Fang et al. Design and modeling for computer experiments, 2006
101
+ assert_allclose(qmc.discrepancy(space_1), 0.0081, atol=1e-4)
102
+ assert_allclose(qmc.discrepancy(space_2), 0.0105, atol=1e-4)
103
+
104
+ # From Zhou Y.-D. et al. Mixture discrepancy for quasi-random point
105
+ # sets. Journal of Complexity, 29 (3-4), pp. 283-301, 2013.
106
+ # Example 4 on Page 298
107
+ sample = np.array([[2, 1, 1, 2, 2, 2],
108
+ [1, 2, 2, 2, 2, 2],
109
+ [2, 1, 1, 1, 1, 1],
110
+ [1, 1, 1, 1, 2, 2],
111
+ [1, 2, 2, 2, 1, 1],
112
+ [2, 2, 2, 2, 1, 1],
113
+ [2, 2, 2, 1, 2, 2]])
114
+ sample = (2.0 * sample - 1.0) / (2.0 * 2.0)
115
+
116
+ assert_allclose(qmc.discrepancy(sample, method='MD'), 2.5000,
117
+ atol=1e-4)
118
+ assert_allclose(qmc.discrepancy(sample, method='WD'), 1.3680,
119
+ atol=1e-4)
120
+ assert_allclose(qmc.discrepancy(sample, method='CD'), 0.3172,
121
+ atol=1e-4)
122
+
123
+ # From Tim P. et al. Minimizing the L2 and Linf star discrepancies
124
+ # of a single point in the unit hypercube. JCAM, 2005
125
+ # Table 1 on Page 283
126
+ for dim in [2, 4, 8, 16, 32, 64]:
127
+ ref = np.sqrt(3**(-dim))
128
+ assert_allclose(qmc.discrepancy(np.array([[1]*dim]),
129
+ method='L2-star'), ref)
130
+
131
+ def test_discrepancy_errors(self):
132
+ sample = np.array([[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]])
133
+
134
+ with pytest.raises(
135
+ ValueError, match=r"Sample is not in unit hypercube"
136
+ ):
137
+ qmc.discrepancy(sample)
138
+
139
+ with pytest.raises(ValueError, match=r"Sample is not a 2D array"):
140
+ qmc.discrepancy([1, 3])
141
+
142
+ sample = [[0, 0], [1, 1], [0.5, 0.5]]
143
+ with pytest.raises(ValueError, match=r"'toto' is not a valid ..."):
144
+ qmc.discrepancy(sample, method="toto")
145
+
146
+ def test_discrepancy_parallel(self, monkeypatch):
147
+ sample = np.array([[2, 1, 1, 2, 2, 2],
148
+ [1, 2, 2, 2, 2, 2],
149
+ [2, 1, 1, 1, 1, 1],
150
+ [1, 1, 1, 1, 2, 2],
151
+ [1, 2, 2, 2, 1, 1],
152
+ [2, 2, 2, 2, 1, 1],
153
+ [2, 2, 2, 1, 2, 2]])
154
+ sample = (2.0 * sample - 1.0) / (2.0 * 2.0)
155
+
156
+ assert_allclose(qmc.discrepancy(sample, method='MD', workers=8),
157
+ 2.5000,
158
+ atol=1e-4)
159
+ assert_allclose(qmc.discrepancy(sample, method='WD', workers=8),
160
+ 1.3680,
161
+ atol=1e-4)
162
+ assert_allclose(qmc.discrepancy(sample, method='CD', workers=8),
163
+ 0.3172,
164
+ atol=1e-4)
165
+
166
+ # From Tim P. et al. Minimizing the L2 and Linf star discrepancies
167
+ # of a single point in the unit hypercube. JCAM, 2005
168
+ # Table 1 on Page 283
169
+ for dim in [2, 4, 8, 16, 32, 64]:
170
+ ref = np.sqrt(3 ** (-dim))
171
+ assert_allclose(qmc.discrepancy(np.array([[1] * dim]),
172
+ method='L2-star', workers=-1), ref)
173
+
174
+ monkeypatch.setattr(os, 'cpu_count', lambda: None)
175
+ with pytest.raises(NotImplementedError, match="Cannot determine the"):
176
+ qmc.discrepancy(sample, workers=-1)
177
+
178
+ with pytest.raises(ValueError, match="Invalid number of workers..."):
179
+ qmc.discrepancy(sample, workers=-2)
180
+
181
+ def test_geometric_discrepancy_errors(self):
182
+ sample = np.array([[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]])
183
+
184
+ with pytest.raises(ValueError, match=r"Sample is not in unit hypercube"):
185
+ qmc.geometric_discrepancy(sample)
186
+
187
+ with pytest.raises(ValueError, match=r"Sample is not a 2D array"):
188
+ qmc.geometric_discrepancy([1, 3])
189
+
190
+ sample = [[0, 0], [1, 1], [0.5, 0.5]]
191
+ with pytest.raises(ValueError, match=r"'toto' is not a valid ..."):
192
+ qmc.geometric_discrepancy(sample, method="toto")
193
+
194
+ sample = np.array([[0, 0], [0, 0], [0, 1]])
195
+ with pytest.warns(UserWarning, match="Sample contains duplicate points."):
196
+ qmc.geometric_discrepancy(sample)
197
+
198
+ sample = np.array([[0.5, 0.5]])
199
+ with pytest.raises(ValueError, match="Sample must contain at least two points"):
200
+ qmc.geometric_discrepancy(sample)
201
+
202
+ def test_geometric_discrepancy(self):
203
+ sample = np.array([[0, 0], [1, 1]])
204
+ assert_allclose(qmc.geometric_discrepancy(sample), np.sqrt(2))
205
+ assert_allclose(qmc.geometric_discrepancy(sample, method="mst"), np.sqrt(2))
206
+
207
+ sample = np.array([[0, 0], [0, 1], [0.5, 1]])
208
+ assert_allclose(qmc.geometric_discrepancy(sample), 0.5)
209
+ assert_allclose(qmc.geometric_discrepancy(sample, method="mst"), 0.75)
210
+
211
+ sample = np.array([[0, 0], [0.25, 0.25], [1, 1]])
212
+ assert_allclose(qmc.geometric_discrepancy(sample), np.sqrt(2) / 4)
213
+ assert_allclose(qmc.geometric_discrepancy(sample, method="mst"), np.sqrt(2) / 2)
214
+ assert_allclose(qmc.geometric_discrepancy(sample, metric="chebyshev"), 0.25)
215
+ assert_allclose(
216
+ qmc.geometric_discrepancy(sample, method="mst", metric="chebyshev"), 0.5
217
+ )
218
+
219
+ rng = np.random.default_rng(191468432622931918890291693003068437394)
220
+ sample = qmc.LatinHypercube(d=3, seed=rng).random(50)
221
+ assert_allclose(qmc.geometric_discrepancy(sample), 0.05106012076093356)
222
+ assert_allclose(
223
+ qmc.geometric_discrepancy(sample, method='mst'), 0.19704396643366182
224
+ )
225
+
226
+ @pytest.mark.xfail(
227
+ reason="minimum_spanning_tree ignores zero distances (#18892)",
228
+ strict=True,
229
+ )
230
+ def test_geometric_discrepancy_mst_with_zero_distances(self):
231
+ sample = np.array([[0, 0], [0, 0], [0, 1]])
232
+ assert_allclose(qmc.geometric_discrepancy(sample, method='mst'), 0.5)
233
+
234
+ def test_update_discrepancy(self):
235
+ # From Fang et al. Design and modeling for computer experiments, 2006
236
+ space_1 = np.array([[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]])
237
+ space_1 = (2.0 * space_1 - 1.0) / (2.0 * 6.0)
238
+
239
+ disc_init = qmc.discrepancy(space_1[:-1], iterative=True)
240
+ disc_iter = update_discrepancy(space_1[-1], space_1[:-1], disc_init)
241
+
242
+ assert_allclose(disc_iter, 0.0081, atol=1e-4)
243
+
244
+ # n<d
245
+ rng = np.random.default_rng(241557431858162136881731220526394276199)
246
+ space_1 = rng.random((4, 10))
247
+
248
+ disc_ref = qmc.discrepancy(space_1)
249
+ disc_init = qmc.discrepancy(space_1[:-1], iterative=True)
250
+ disc_iter = update_discrepancy(space_1[-1], space_1[:-1], disc_init)
251
+
252
+ assert_allclose(disc_iter, disc_ref, atol=1e-4)
253
+
254
+ # errors
255
+ with pytest.raises(ValueError, match=r"Sample is not in unit "
256
+ r"hypercube"):
257
+ update_discrepancy(space_1[-1], space_1[:-1] + 1, disc_init)
258
+
259
+ with pytest.raises(ValueError, match=r"Sample is not a 2D array"):
260
+ update_discrepancy(space_1[-1], space_1[0], disc_init)
261
+
262
+ x_new = [1, 3]
263
+ with pytest.raises(ValueError, match=r"x_new is not in unit "
264
+ r"hypercube"):
265
+ update_discrepancy(x_new, space_1[:-1], disc_init)
266
+
267
+ x_new = [[0.5, 0.5]]
268
+ with pytest.raises(ValueError, match=r"x_new is not a 1D array"):
269
+ update_discrepancy(x_new, space_1[:-1], disc_init)
270
+
271
+ x_new = [0.3, 0.1, 0]
272
+ with pytest.raises(ValueError, match=r"x_new and sample must be "
273
+ r"broadcastable"):
274
+ update_discrepancy(x_new, space_1[:-1], disc_init)
275
+
276
+ def test_perm_discrepancy(self):
277
+ rng = np.random.default_rng(46449423132557934943847369749645759997)
278
+ qmc_gen = qmc.LatinHypercube(5, seed=rng)
279
+ sample = qmc_gen.random(10)
280
+ disc = qmc.discrepancy(sample)
281
+
282
+ for i in range(100):
283
+ row_1 = rng.integers(10)
284
+ row_2 = rng.integers(10)
285
+ col = rng.integers(5)
286
+
287
+ disc = _perturb_discrepancy(sample, row_1, row_2, col, disc)
288
+ sample[row_1, col], sample[row_2, col] = (
289
+ sample[row_2, col], sample[row_1, col])
290
+ disc_reference = qmc.discrepancy(sample)
291
+ assert_allclose(disc, disc_reference)
292
+
293
+ def test_discrepancy_alternative_implementation(self):
294
+ """Alternative definitions from Matt Haberland."""
295
+
296
+ def disc_c2(x):
297
+ n, s = x.shape
298
+ xij = x
299
+ disc1 = np.sum(np.prod((1
300
+ + 1/2*np.abs(xij-0.5)
301
+ - 1/2*np.abs(xij-0.5)**2), axis=1))
302
+ xij = x[None, :, :]
303
+ xkj = x[:, None, :]
304
+ disc2 = np.sum(np.sum(np.prod(1
305
+ + 1/2*np.abs(xij - 0.5)
306
+ + 1/2*np.abs(xkj - 0.5)
307
+ - 1/2*np.abs(xij - xkj), axis=2),
308
+ axis=0))
309
+ return (13/12)**s - 2/n * disc1 + 1/n**2*disc2
310
+
311
+ def disc_wd(x):
312
+ n, s = x.shape
313
+ xij = x[None, :, :]
314
+ xkj = x[:, None, :]
315
+ disc = np.sum(np.sum(np.prod(3/2
316
+ - np.abs(xij - xkj)
317
+ + np.abs(xij - xkj)**2, axis=2),
318
+ axis=0))
319
+ return -(4/3)**s + 1/n**2 * disc
320
+
321
+ def disc_md(x):
322
+ n, s = x.shape
323
+ xij = x
324
+ disc1 = np.sum(np.prod((5/3
325
+ - 1/4*np.abs(xij-0.5)
326
+ - 1/4*np.abs(xij-0.5)**2), axis=1))
327
+ xij = x[None, :, :]
328
+ xkj = x[:, None, :]
329
+ disc2 = np.sum(np.sum(np.prod(15/8
330
+ - 1/4*np.abs(xij - 0.5)
331
+ - 1/4*np.abs(xkj - 0.5)
332
+ - 3/4*np.abs(xij - xkj)
333
+ + 1/2*np.abs(xij - xkj)**2,
334
+ axis=2), axis=0))
335
+ return (19/12)**s - 2/n * disc1 + 1/n**2*disc2
336
+
337
+ def disc_star_l2(x):
338
+ n, s = x.shape
339
+ return np.sqrt(
340
+ 3 ** (-s) - 2 ** (1 - s) / n
341
+ * np.sum(np.prod(1 - x ** 2, axis=1))
342
+ + np.sum([
343
+ np.prod(1 - np.maximum(x[k, :], x[j, :]))
344
+ for k in range(n) for j in range(n)
345
+ ]) / n ** 2
346
+ )
347
+
348
+ rng = np.random.default_rng(117065081482921065782761407107747179201)
349
+ sample = rng.random((30, 10))
350
+
351
+ disc_curr = qmc.discrepancy(sample, method='CD')
352
+ disc_alt = disc_c2(sample)
353
+ assert_allclose(disc_curr, disc_alt)
354
+
355
+ disc_curr = qmc.discrepancy(sample, method='WD')
356
+ disc_alt = disc_wd(sample)
357
+ assert_allclose(disc_curr, disc_alt)
358
+
359
+ disc_curr = qmc.discrepancy(sample, method='MD')
360
+ disc_alt = disc_md(sample)
361
+ assert_allclose(disc_curr, disc_alt)
362
+
363
+ disc_curr = qmc.discrepancy(sample, method='L2-star')
364
+ disc_alt = disc_star_l2(sample)
365
+ assert_allclose(disc_curr, disc_alt)
366
+
367
+ def test_n_primes(self):
368
+ primes = n_primes(10)
369
+ assert primes[-1] == 29
370
+
371
+ primes = n_primes(168)
372
+ assert primes[-1] == 997
373
+
374
+ primes = n_primes(350)
375
+ assert primes[-1] == 2357
376
+
377
+ def test_primes(self):
378
+ primes = primes_from_2_to(50)
379
+ out = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
380
+ assert_allclose(primes, out)
381
+
382
+
383
+ class TestVDC:
384
+ def test_van_der_corput(self):
385
+ sample = van_der_corput(10)
386
+ out = [0.0, 0.5, 0.25, 0.75, 0.125, 0.625,
387
+ 0.375, 0.875, 0.0625, 0.5625]
388
+ assert_allclose(sample, out)
389
+
390
+ sample = van_der_corput(10, workers=4)
391
+ assert_allclose(sample, out)
392
+
393
+ sample = van_der_corput(10, workers=8)
394
+ assert_allclose(sample, out)
395
+
396
+ sample = van_der_corput(7, start_index=3)
397
+ assert_allclose(sample, out[3:])
398
+
399
+ def test_van_der_corput_scramble(self):
400
+ seed = 338213789010180879520345496831675783177
401
+ out = van_der_corput(10, scramble=True, seed=seed)
402
+
403
+ sample = van_der_corput(7, start_index=3, scramble=True, seed=seed)
404
+ assert_allclose(sample, out[3:])
405
+
406
+ sample = van_der_corput(
407
+ 7, start_index=3, scramble=True, seed=seed, workers=4
408
+ )
409
+ assert_allclose(sample, out[3:])
410
+
411
+ sample = van_der_corput(
412
+ 7, start_index=3, scramble=True, seed=seed, workers=8
413
+ )
414
+ assert_allclose(sample, out[3:])
415
+
416
+ def test_invalid_base_error(self):
417
+ with pytest.raises(ValueError, match=r"'base' must be at least 2"):
418
+ van_der_corput(10, base=1)
419
+
420
+
421
+ class RandomEngine(qmc.QMCEngine):
422
+ def __init__(self, d, optimization=None, seed=None):
423
+ super().__init__(d=d, optimization=optimization, seed=seed)
424
+
425
+ def _random(self, n=1, *, workers=1):
426
+ sample = self.rng.random((n, self.d))
427
+ return sample
428
+
429
+
430
+ def test_subclassing_QMCEngine():
431
+ engine = RandomEngine(2, seed=175180605424926556207367152557812293274)
432
+
433
+ sample_1 = engine.random(n=5)
434
+ sample_2 = engine.random(n=7)
435
+ assert engine.num_generated == 12
436
+
437
+ # reset and re-sample
438
+ engine.reset()
439
+ assert engine.num_generated == 0
440
+
441
+ sample_1_test = engine.random(n=5)
442
+ assert_equal(sample_1, sample_1_test)
443
+
444
+ # repeat reset and fast forward
445
+ engine.reset()
446
+ engine.fast_forward(n=5)
447
+ sample_2_test = engine.random(n=7)
448
+
449
+ assert_equal(sample_2, sample_2_test)
450
+ assert engine.num_generated == 12
451
+
452
+
453
+ def test_raises():
454
+ # input validation
455
+ with pytest.raises(ValueError, match=r"d must be a non-negative integer"):
456
+ RandomEngine((2,))
457
+
458
+ with pytest.raises(ValueError, match=r"d must be a non-negative integer"):
459
+ RandomEngine(-1)
460
+
461
+ msg = r"'u_bounds' and 'l_bounds' must be integers"
462
+ with pytest.raises(ValueError, match=msg):
463
+ engine = RandomEngine(1)
464
+ engine.integers(l_bounds=1, u_bounds=1.1)
465
+
466
+
467
+ def test_integers():
468
+ engine = RandomEngine(1, seed=231195739755290648063853336582377368684)
469
+
470
+ # basic tests
471
+ sample = engine.integers(1, n=10)
472
+ assert_equal(np.unique(sample), [0])
473
+
474
+ assert sample.dtype == np.dtype('int64')
475
+
476
+ sample = engine.integers(1, n=10, endpoint=True)
477
+ assert_equal(np.unique(sample), [0, 1])
478
+
479
+ low = -5
480
+ high = 7
481
+
482
+ # scaling logic
483
+ engine.reset()
484
+ ref_sample = engine.random(20)
485
+ ref_sample = ref_sample * (high - low) + low
486
+ ref_sample = np.floor(ref_sample).astype(np.int64)
487
+
488
+ engine.reset()
489
+ sample = engine.integers(low, u_bounds=high, n=20, endpoint=False)
490
+
491
+ assert_equal(sample, ref_sample)
492
+
493
+ # up to bounds, no less, no more
494
+ sample = engine.integers(low, u_bounds=high, n=100, endpoint=False)
495
+ assert_equal((sample.min(), sample.max()), (low, high-1))
496
+
497
+ sample = engine.integers(low, u_bounds=high, n=100, endpoint=True)
498
+ assert_equal((sample.min(), sample.max()), (low, high))
499
+
500
+
501
+ def test_integers_nd():
502
+ d = 10
503
+ rng = np.random.default_rng(3716505122102428560615700415287450951)
504
+ low = rng.integers(low=-5, high=-1, size=d)
505
+ high = rng.integers(low=1, high=5, size=d, endpoint=True)
506
+ engine = RandomEngine(d, seed=rng)
507
+
508
+ sample = engine.integers(low, u_bounds=high, n=100, endpoint=False)
509
+ assert_equal(sample.min(axis=0), low)
510
+ assert_equal(sample.max(axis=0), high-1)
511
+
512
+ sample = engine.integers(low, u_bounds=high, n=100, endpoint=True)
513
+ assert_equal(sample.min(axis=0), low)
514
+ assert_equal(sample.max(axis=0), high)
515
+
516
+
517
+ class QMCEngineTests:
518
+ """Generic tests for QMC engines."""
519
+ qmce = NotImplemented
520
+ can_scramble = NotImplemented
521
+ unscramble_nd = NotImplemented
522
+ scramble_nd = NotImplemented
523
+
524
+ scramble = [True, False]
525
+ ids = ["Scrambled", "Unscrambled"]
526
+
527
+ def engine(
528
+ self, scramble: bool,
529
+ seed=170382760648021597650530316304495310428,
530
+ **kwargs
531
+ ) -> QMCEngine:
532
+ if self.can_scramble:
533
+ return self.qmce(scramble=scramble, seed=seed, **kwargs)
534
+ else:
535
+ if scramble:
536
+ pytest.skip()
537
+ else:
538
+ return self.qmce(seed=seed, **kwargs)
539
+
540
+ def reference(self, scramble: bool) -> np.ndarray:
541
+ return self.scramble_nd if scramble else self.unscramble_nd
542
+
543
+ @pytest.mark.parametrize("scramble", scramble, ids=ids)
544
+ def test_0dim(self, scramble):
545
+ engine = self.engine(d=0, scramble=scramble)
546
+ sample = engine.random(4)
547
+ assert_array_equal(np.empty((4, 0)), sample)
548
+
549
+ @pytest.mark.parametrize("scramble", scramble, ids=ids)
550
+ def test_0sample(self, scramble):
551
+ engine = self.engine(d=2, scramble=scramble)
552
+ sample = engine.random(0)
553
+ assert_array_equal(np.empty((0, 2)), sample)
554
+
555
+ @pytest.mark.parametrize("scramble", scramble, ids=ids)
556
+ def test_1sample(self, scramble):
557
+ engine = self.engine(d=2, scramble=scramble)
558
+ sample = engine.random(1)
559
+ assert (1, 2) == sample.shape
560
+
561
+ @pytest.mark.parametrize("scramble", scramble, ids=ids)
562
+ def test_bounds(self, scramble):
563
+ engine = self.engine(d=100, scramble=scramble)
564
+ sample = engine.random(512)
565
+ assert np.all(sample >= 0)
566
+ assert np.all(sample <= 1)
567
+
568
+ @pytest.mark.parametrize("scramble", scramble, ids=ids)
569
+ def test_sample(self, scramble):
570
+ ref_sample = self.reference(scramble=scramble)
571
+ engine = self.engine(d=2, scramble=scramble)
572
+ sample = engine.random(n=len(ref_sample))
573
+
574
+ assert_allclose(sample, ref_sample, atol=1e-1)
575
+ assert engine.num_generated == len(ref_sample)
576
+
577
+ @pytest.mark.parametrize("scramble", scramble, ids=ids)
578
+ def test_continuing(self, scramble):
579
+ engine = self.engine(d=2, scramble=scramble)
580
+ ref_sample = engine.random(n=8)
581
+
582
+ engine = self.engine(d=2, scramble=scramble)
583
+
584
+ n_half = len(ref_sample) // 2
585
+
586
+ _ = engine.random(n=n_half)
587
+ sample = engine.random(n=n_half)
588
+ assert_allclose(sample, ref_sample[n_half:], atol=1e-1)
589
+
590
+ @pytest.mark.parametrize("scramble", scramble, ids=ids)
591
+ @pytest.mark.parametrize(
592
+ "seed",
593
+ (
594
+ 170382760648021597650530316304495310428,
595
+ np.random.default_rng(170382760648021597650530316304495310428),
596
+ None,
597
+ ),
598
+ )
599
+ def test_reset(self, scramble, seed):
600
+ engine = self.engine(d=2, scramble=scramble, seed=seed)
601
+ ref_sample = engine.random(n=8)
602
+
603
+ engine.reset()
604
+ assert engine.num_generated == 0
605
+
606
+ sample = engine.random(n=8)
607
+ assert_allclose(sample, ref_sample)
608
+
609
+ @pytest.mark.parametrize("scramble", scramble, ids=ids)
610
+ def test_fast_forward(self, scramble):
611
+ engine = self.engine(d=2, scramble=scramble)
612
+ ref_sample = engine.random(n=8)
613
+
614
+ engine = self.engine(d=2, scramble=scramble)
615
+
616
+ engine.fast_forward(4)
617
+ sample = engine.random(n=4)
618
+
619
+ assert_allclose(sample, ref_sample[4:], atol=1e-1)
620
+
621
+ # alternate fast forwarding with sampling
622
+ engine.reset()
623
+ even_draws = []
624
+ for i in range(8):
625
+ if i % 2 == 0:
626
+ even_draws.append(engine.random())
627
+ else:
628
+ engine.fast_forward(1)
629
+ assert_allclose(
630
+ ref_sample[[i for i in range(8) if i % 2 == 0]],
631
+ np.concatenate(even_draws),
632
+ atol=1e-5
633
+ )
634
+
635
+ @pytest.mark.parametrize("scramble", [True])
636
+ def test_distribution(self, scramble):
637
+ d = 50
638
+ engine = self.engine(d=d, scramble=scramble)
639
+ sample = engine.random(1024)
640
+ assert_allclose(
641
+ np.mean(sample, axis=0), np.repeat(0.5, d), atol=1e-2
642
+ )
643
+ assert_allclose(
644
+ np.percentile(sample, 25, axis=0), np.repeat(0.25, d), atol=1e-2
645
+ )
646
+ assert_allclose(
647
+ np.percentile(sample, 75, axis=0), np.repeat(0.75, d), atol=1e-2
648
+ )
649
+
650
+ def test_raises_optimizer(self):
651
+ message = r"'toto' is not a valid optimization method"
652
+ with pytest.raises(ValueError, match=message):
653
+ self.engine(d=1, scramble=False, optimization="toto")
654
+
655
+ @pytest.mark.parametrize(
656
+ "optimization,metric",
657
+ [
658
+ ("random-CD", qmc.discrepancy),
659
+ ("lloyd", lambda sample: -_l1_norm(sample))]
660
+ )
661
+ def test_optimizers(self, optimization, metric):
662
+ engine = self.engine(d=2, scramble=False)
663
+ sample_ref = engine.random(n=64)
664
+ metric_ref = metric(sample_ref)
665
+
666
+ optimal_ = self.engine(d=2, scramble=False, optimization=optimization)
667
+ sample_ = optimal_.random(n=64)
668
+ metric_ = metric(sample_)
669
+
670
+ assert metric_ < metric_ref
671
+
672
+ def test_consume_prng_state(self):
673
+ rng = np.random.default_rng(0xa29cabb11cfdf44ff6cac8bec254c2a0)
674
+ sample = []
675
+ for i in range(3):
676
+ engine = self.engine(d=2, scramble=True, seed=rng)
677
+ sample.append(engine.random(4))
678
+
679
+ with pytest.raises(AssertionError, match="Arrays are not equal"):
680
+ assert_equal(sample[0], sample[1])
681
+ with pytest.raises(AssertionError, match="Arrays are not equal"):
682
+ assert_equal(sample[0], sample[2])
683
+
684
+
685
+ class TestHalton(QMCEngineTests):
686
+ qmce = qmc.Halton
687
+ can_scramble = True
688
+ # theoretical values known from Van der Corput
689
+ unscramble_nd = np.array([[0, 0], [1 / 2, 1 / 3],
690
+ [1 / 4, 2 / 3], [3 / 4, 1 / 9],
691
+ [1 / 8, 4 / 9], [5 / 8, 7 / 9],
692
+ [3 / 8, 2 / 9], [7 / 8, 5 / 9]])
693
+ # theoretical values unknown: convergence properties checked
694
+ scramble_nd = np.array([[0.50246036, 0.93382481],
695
+ [0.00246036, 0.26715815],
696
+ [0.75246036, 0.60049148],
697
+ [0.25246036, 0.8227137 ],
698
+ [0.62746036, 0.15604704],
699
+ [0.12746036, 0.48938037],
700
+ [0.87746036, 0.71160259],
701
+ [0.37746036, 0.04493592]])
702
+
703
+ def test_workers(self):
704
+ ref_sample = self.reference(scramble=True)
705
+ engine = self.engine(d=2, scramble=True)
706
+ sample = engine.random(n=len(ref_sample), workers=8)
707
+
708
+ assert_allclose(sample, ref_sample, atol=1e-3)
709
+
710
+ # worker + integers
711
+ engine.reset()
712
+ ref_sample = engine.integers(10)
713
+ engine.reset()
714
+ sample = engine.integers(10, workers=8)
715
+ assert_equal(sample, ref_sample)
716
+
717
+
718
+ class TestLHS(QMCEngineTests):
719
+ qmce = qmc.LatinHypercube
720
+ can_scramble = True
721
+
722
+ def test_continuing(self, *args):
723
+ pytest.skip("Not applicable: not a sequence.")
724
+
725
+ def test_fast_forward(self, *args):
726
+ pytest.skip("Not applicable: not a sequence.")
727
+
728
+ def test_sample(self, *args):
729
+ pytest.skip("Not applicable: the value of reference sample is"
730
+ " implementation dependent.")
731
+
732
+ @pytest.mark.parametrize("strength", [1, 2])
733
+ @pytest.mark.parametrize("scramble", [False, True])
734
+ @pytest.mark.parametrize("optimization", [None, "random-CD"])
735
+ def test_sample_stratified(self, optimization, scramble, strength):
736
+ seed = np.random.default_rng(37511836202578819870665127532742111260)
737
+ p = 5
738
+ n = p**2
739
+ d = 6
740
+
741
+ engine = qmc.LatinHypercube(d=d, scramble=scramble,
742
+ strength=strength,
743
+ optimization=optimization,
744
+ seed=seed)
745
+ sample = engine.random(n=n)
746
+ assert sample.shape == (n, d)
747
+ assert engine.num_generated == n
748
+
749
+ # centering stratifies samples in the middle of equal segments:
750
+ # * inter-sample distance is constant in 1D sub-projections
751
+ # * after ordering, columns are equal
752
+ expected1d = (np.arange(n) + 0.5) / n
753
+ expected = np.broadcast_to(expected1d, (d, n)).T
754
+ assert np.any(sample != expected)
755
+
756
+ sorted_sample = np.sort(sample, axis=0)
757
+ tol = 0.5 / n if scramble else 0
758
+
759
+ assert_allclose(sorted_sample, expected, atol=tol)
760
+ assert np.any(sample - expected > tol)
761
+
762
+ if strength == 2 and optimization is None:
763
+ unique_elements = np.arange(p)
764
+ desired = set(product(unique_elements, unique_elements))
765
+
766
+ for i, j in combinations(range(engine.d), 2):
767
+ samples_2d = sample[:, [i, j]]
768
+ res = (samples_2d * p).astype(int)
769
+ res_set = {tuple(row) for row in res}
770
+ assert_equal(res_set, desired)
771
+
772
+ def test_optimizer_1d(self):
773
+ # discrepancy measures are invariant under permuting factors and runs
774
+ engine = self.engine(d=1, scramble=False)
775
+ sample_ref = engine.random(n=64)
776
+
777
+ optimal_ = self.engine(d=1, scramble=False, optimization="random-CD")
778
+ sample_ = optimal_.random(n=64)
779
+
780
+ assert_array_equal(sample_ref, sample_)
781
+
782
+ def test_raises(self):
783
+ message = r"not a valid strength"
784
+ with pytest.raises(ValueError, match=message):
785
+ qmc.LatinHypercube(1, strength=3)
786
+
787
+ message = r"n is not the square of a prime number"
788
+ with pytest.raises(ValueError, match=message):
789
+ engine = qmc.LatinHypercube(d=2, strength=2)
790
+ engine.random(16)
791
+
792
+ message = r"n is not the square of a prime number"
793
+ with pytest.raises(ValueError, match=message):
794
+ engine = qmc.LatinHypercube(d=2, strength=2)
795
+ engine.random(5) # because int(sqrt(5)) would result in 2
796
+
797
+ message = r"n is too small for d"
798
+ with pytest.raises(ValueError, match=message):
799
+ engine = qmc.LatinHypercube(d=5, strength=2)
800
+ engine.random(9)
801
+
802
+
803
+ class TestSobol(QMCEngineTests):
804
+ qmce = qmc.Sobol
805
+ can_scramble = True
806
+ # theoretical values from Joe Kuo2010
807
+ unscramble_nd = np.array([[0., 0.],
808
+ [0.5, 0.5],
809
+ [0.75, 0.25],
810
+ [0.25, 0.75],
811
+ [0.375, 0.375],
812
+ [0.875, 0.875],
813
+ [0.625, 0.125],
814
+ [0.125, 0.625]])
815
+
816
+ # theoretical values unknown: convergence properties checked
817
+ scramble_nd = np.array([[0.25331921, 0.41371179],
818
+ [0.8654213, 0.9821167],
819
+ [0.70097554, 0.03664616],
820
+ [0.18027647, 0.60895735],
821
+ [0.10521339, 0.21897069],
822
+ [0.53019685, 0.66619033],
823
+ [0.91122276, 0.34580743],
824
+ [0.45337471, 0.78912079]])
825
+
826
+ def test_warning(self):
827
+ with pytest.warns(UserWarning, match=r"The balance properties of "
828
+ r"Sobol' points"):
829
+ engine = qmc.Sobol(1)
830
+ engine.random(10)
831
+
832
+ def test_random_base2(self):
833
+ engine = qmc.Sobol(2, scramble=False)
834
+ sample = engine.random_base2(2)
835
+ assert_array_equal(self.unscramble_nd[:4], sample)
836
+
837
+ # resampling still having N=2**n
838
+ sample = engine.random_base2(2)
839
+ assert_array_equal(self.unscramble_nd[4:8], sample)
840
+
841
+ # resampling again but leading to N!=2**n
842
+ with pytest.raises(ValueError, match=r"The balance properties of "
843
+ r"Sobol' points"):
844
+ engine.random_base2(2)
845
+
846
+ def test_raise(self):
847
+ with pytest.raises(ValueError, match=r"Maximum supported "
848
+ r"dimensionality"):
849
+ qmc.Sobol(qmc.Sobol.MAXDIM + 1)
850
+
851
+ with pytest.raises(ValueError, match=r"Maximum supported "
852
+ r"'bits' is 64"):
853
+ qmc.Sobol(1, bits=65)
854
+
855
+ def test_high_dim(self):
856
+ engine = qmc.Sobol(1111, scramble=False)
857
+ count1 = Counter(engine.random().flatten().tolist())
858
+ count2 = Counter(engine.random().flatten().tolist())
859
+ assert_equal(count1, Counter({0.0: 1111}))
860
+ assert_equal(count2, Counter({0.5: 1111}))
861
+
862
+ @pytest.mark.parametrize("bits", [2, 3])
863
+ def test_bits(self, bits):
864
+ engine = qmc.Sobol(2, scramble=False, bits=bits)
865
+ ns = 2**bits
866
+ sample = engine.random(ns)
867
+ assert_array_equal(self.unscramble_nd[:ns], sample)
868
+
869
+ with pytest.raises(ValueError, match="increasing `bits`"):
870
+ engine.random()
871
+
872
+ def test_64bits(self):
873
+ engine = qmc.Sobol(2, scramble=False, bits=64)
874
+ sample = engine.random(8)
875
+ assert_array_equal(self.unscramble_nd, sample)
876
+
877
+
878
+ class TestPoisson(QMCEngineTests):
879
+ qmce = qmc.PoissonDisk
880
+ can_scramble = False
881
+
882
+ def test_bounds(self, *args):
883
+ pytest.skip("Too costly in memory.")
884
+
885
+ def test_fast_forward(self, *args):
886
+ pytest.skip("Not applicable: recursive process.")
887
+
888
+ def test_sample(self, *args):
889
+ pytest.skip("Not applicable: the value of reference sample is"
890
+ " implementation dependent.")
891
+
892
+ def test_continuing(self, *args):
893
+ # can continue a sampling, but will not preserve the same order
894
+ # because candidates are lost, so we will not select the same center
895
+ radius = 0.05
896
+ ns = 6
897
+ engine = self.engine(d=2, radius=radius, scramble=False)
898
+
899
+ sample_init = engine.random(n=ns)
900
+ assert len(sample_init) <= ns
901
+ assert l2_norm(sample_init) >= radius
902
+
903
+ sample_continued = engine.random(n=ns)
904
+ assert len(sample_continued) <= ns
905
+ assert l2_norm(sample_continued) >= radius
906
+
907
+ sample = np.concatenate([sample_init, sample_continued], axis=0)
908
+ assert len(sample) <= ns * 2
909
+ assert l2_norm(sample) >= radius
910
+
911
+ def test_mindist(self):
912
+ rng = np.random.default_rng(132074951149370773672162394161442690287)
913
+ ns = 50
914
+
915
+ low, high = 0.08, 0.2
916
+ radii = (high - low) * rng.random(5) + low
917
+
918
+ dimensions = [1, 3, 4]
919
+ hypersphere_methods = ["volume", "surface"]
920
+
921
+ gen = product(dimensions, radii, hypersphere_methods)
922
+
923
+ for d, radius, hypersphere in gen:
924
+ engine = self.qmce(
925
+ d=d, radius=radius, hypersphere=hypersphere, seed=rng
926
+ )
927
+ sample = engine.random(ns)
928
+
929
+ assert len(sample) <= ns
930
+ assert l2_norm(sample) >= radius
931
+
932
+ def test_fill_space(self):
933
+ radius = 0.2
934
+ engine = self.qmce(d=2, radius=radius)
935
+
936
+ sample = engine.fill_space()
937
+ # circle packing problem is np complex
938
+ assert l2_norm(sample) >= radius
939
+
940
+ def test_raises(self):
941
+ message = r"'toto' is not a valid hypersphere sampling"
942
+ with pytest.raises(ValueError, match=message):
943
+ qmc.PoissonDisk(1, hypersphere="toto")
944
+
945
+
946
+ class TestMultinomialQMC:
947
+ def test_validations(self):
948
+ # negative Ps
949
+ p = np.array([0.12, 0.26, -0.05, 0.35, 0.22])
950
+ with pytest.raises(ValueError, match=r"Elements of pvals must "
951
+ r"be non-negative."):
952
+ qmc.MultinomialQMC(p, n_trials=10)
953
+
954
+ # sum of P too large
955
+ p = np.array([0.12, 0.26, 0.1, 0.35, 0.22])
956
+ message = r"Elements of pvals must sum to 1."
957
+ with pytest.raises(ValueError, match=message):
958
+ qmc.MultinomialQMC(p, n_trials=10)
959
+
960
+ p = np.array([0.12, 0.26, 0.05, 0.35, 0.22])
961
+
962
+ message = r"Dimension of `engine` must be 1."
963
+ with pytest.raises(ValueError, match=message):
964
+ qmc.MultinomialQMC(p, n_trials=10, engine=qmc.Sobol(d=2))
965
+
966
+ message = r"`engine` must be an instance of..."
967
+ with pytest.raises(ValueError, match=message):
968
+ qmc.MultinomialQMC(p, n_trials=10, engine=np.random.default_rng())
969
+
970
+ @pytest.mark.filterwarnings('ignore::UserWarning')
971
+ def test_MultinomialBasicDraw(self):
972
+ seed = np.random.default_rng(6955663962957011631562466584467607969)
973
+ p = np.array([0.12, 0.26, 0.05, 0.35, 0.22])
974
+ n_trials = 100
975
+ expected = np.atleast_2d(n_trials * p).astype(int)
976
+ engine = qmc.MultinomialQMC(p, n_trials=n_trials, seed=seed)
977
+ assert_allclose(engine.random(1), expected, atol=1)
978
+
979
+ def test_MultinomialDistribution(self):
980
+ seed = np.random.default_rng(77797854505813727292048130876699859000)
981
+ p = np.array([0.12, 0.26, 0.05, 0.35, 0.22])
982
+ engine = qmc.MultinomialQMC(p, n_trials=8192, seed=seed)
983
+ draws = engine.random(1)
984
+ assert_allclose(draws / np.sum(draws), np.atleast_2d(p), atol=1e-4)
985
+
986
+ def test_FindIndex(self):
987
+ p_cumulative = np.array([0.1, 0.4, 0.45, 0.6, 0.75, 0.9, 0.99, 1.0])
988
+ size = len(p_cumulative)
989
+ assert_equal(_test_find_index(p_cumulative, size, 0.0), 0)
990
+ assert_equal(_test_find_index(p_cumulative, size, 0.4), 2)
991
+ assert_equal(_test_find_index(p_cumulative, size, 0.44999), 2)
992
+ assert_equal(_test_find_index(p_cumulative, size, 0.45001), 3)
993
+ assert_equal(_test_find_index(p_cumulative, size, 1.0), size - 1)
994
+
995
+ @pytest.mark.filterwarnings('ignore::UserWarning')
996
+ def test_other_engine(self):
997
+ # same as test_MultinomialBasicDraw with different engine
998
+ seed = np.random.default_rng(283753519042773243071753037669078065412)
999
+ p = np.array([0.12, 0.26, 0.05, 0.35, 0.22])
1000
+ n_trials = 100
1001
+ expected = np.atleast_2d(n_trials * p).astype(int)
1002
+ base_engine = qmc.Sobol(1, scramble=True, seed=seed)
1003
+ engine = qmc.MultinomialQMC(p, n_trials=n_trials, engine=base_engine,
1004
+ seed=seed)
1005
+ assert_allclose(engine.random(1), expected, atol=1)
1006
+
1007
+
1008
+ class TestNormalQMC:
1009
+ def test_NormalQMC(self):
1010
+ # d = 1
1011
+ engine = qmc.MultivariateNormalQMC(mean=np.zeros(1))
1012
+ samples = engine.random()
1013
+ assert_equal(samples.shape, (1, 1))
1014
+ samples = engine.random(n=5)
1015
+ assert_equal(samples.shape, (5, 1))
1016
+ # d = 2
1017
+ engine = qmc.MultivariateNormalQMC(mean=np.zeros(2))
1018
+ samples = engine.random()
1019
+ assert_equal(samples.shape, (1, 2))
1020
+ samples = engine.random(n=5)
1021
+ assert_equal(samples.shape, (5, 2))
1022
+
1023
+ def test_NormalQMCInvTransform(self):
1024
+ # d = 1
1025
+ engine = qmc.MultivariateNormalQMC(
1026
+ mean=np.zeros(1), inv_transform=True)
1027
+ samples = engine.random()
1028
+ assert_equal(samples.shape, (1, 1))
1029
+ samples = engine.random(n=5)
1030
+ assert_equal(samples.shape, (5, 1))
1031
+ # d = 2
1032
+ engine = qmc.MultivariateNormalQMC(
1033
+ mean=np.zeros(2), inv_transform=True)
1034
+ samples = engine.random()
1035
+ assert_equal(samples.shape, (1, 2))
1036
+ samples = engine.random(n=5)
1037
+ assert_equal(samples.shape, (5, 2))
1038
+
1039
+ def test_NormalQMCSeeded(self):
1040
+ # test even dimension
1041
+ seed = np.random.default_rng(274600237797326520096085022671371676017)
1042
+ engine = qmc.MultivariateNormalQMC(
1043
+ mean=np.zeros(2), inv_transform=False, seed=seed)
1044
+ samples = engine.random(n=2)
1045
+ samples_expected = np.array([[-0.932001, -0.522923],
1046
+ [-1.477655, 0.846851]])
1047
+ assert_allclose(samples, samples_expected, atol=1e-4)
1048
+
1049
+ # test odd dimension
1050
+ seed = np.random.default_rng(274600237797326520096085022671371676017)
1051
+ engine = qmc.MultivariateNormalQMC(
1052
+ mean=np.zeros(3), inv_transform=False, seed=seed)
1053
+ samples = engine.random(n=2)
1054
+ samples_expected = np.array([[-0.932001, -0.522923, 0.036578],
1055
+ [-1.778011, 0.912428, -0.065421]])
1056
+ assert_allclose(samples, samples_expected, atol=1e-4)
1057
+
1058
+ # same test with another engine
1059
+ seed = np.random.default_rng(274600237797326520096085022671371676017)
1060
+ base_engine = qmc.Sobol(4, scramble=True, seed=seed)
1061
+ engine = qmc.MultivariateNormalQMC(
1062
+ mean=np.zeros(3), inv_transform=False,
1063
+ engine=base_engine, seed=seed
1064
+ )
1065
+ samples = engine.random(n=2)
1066
+ samples_expected = np.array([[-0.932001, -0.522923, 0.036578],
1067
+ [-1.778011, 0.912428, -0.065421]])
1068
+ assert_allclose(samples, samples_expected, atol=1e-4)
1069
+
1070
+ def test_NormalQMCSeededInvTransform(self):
1071
+ # test even dimension
1072
+ seed = np.random.default_rng(288527772707286126646493545351112463929)
1073
+ engine = qmc.MultivariateNormalQMC(
1074
+ mean=np.zeros(2), seed=seed, inv_transform=True)
1075
+ samples = engine.random(n=2)
1076
+ samples_expected = np.array([[-0.913237, -0.964026],
1077
+ [0.255904, 0.003068]])
1078
+ assert_allclose(samples, samples_expected, atol=1e-4)
1079
+
1080
+ # test odd dimension
1081
+ seed = np.random.default_rng(288527772707286126646493545351112463929)
1082
+ engine = qmc.MultivariateNormalQMC(
1083
+ mean=np.zeros(3), seed=seed, inv_transform=True)
1084
+ samples = engine.random(n=2)
1085
+ samples_expected = np.array([[-0.913237, -0.964026, 0.355501],
1086
+ [0.699261, 2.90213 , -0.6418]])
1087
+ assert_allclose(samples, samples_expected, atol=1e-4)
1088
+
1089
+ def test_other_engine(self):
1090
+ for d in (0, 1, 2):
1091
+ base_engine = qmc.Sobol(d=d, scramble=False)
1092
+ engine = qmc.MultivariateNormalQMC(mean=np.zeros(d),
1093
+ engine=base_engine,
1094
+ inv_transform=True)
1095
+ samples = engine.random()
1096
+ assert_equal(samples.shape, (1, d))
1097
+
1098
+ def test_NormalQMCShapiro(self):
1099
+ rng = np.random.default_rng(13242)
1100
+ engine = qmc.MultivariateNormalQMC(mean=np.zeros(2), seed=rng)
1101
+ samples = engine.random(n=256)
1102
+ assert all(np.abs(samples.mean(axis=0)) < 1e-2)
1103
+ assert all(np.abs(samples.std(axis=0) - 1) < 1e-2)
1104
+ # perform Shapiro-Wilk test for normality
1105
+ for i in (0, 1):
1106
+ _, pval = shapiro(samples[:, i])
1107
+ assert pval > 0.9
1108
+ # make sure samples are uncorrelated
1109
+ cov = np.cov(samples.transpose())
1110
+ assert np.abs(cov[0, 1]) < 1e-2
1111
+
1112
+ def test_NormalQMCShapiroInvTransform(self):
1113
+ rng = np.random.default_rng(32344554)
1114
+ engine = qmc.MultivariateNormalQMC(
1115
+ mean=np.zeros(2), inv_transform=True, seed=rng)
1116
+ samples = engine.random(n=256)
1117
+ assert all(np.abs(samples.mean(axis=0)) < 1e-2)
1118
+ assert all(np.abs(samples.std(axis=0) - 1) < 1e-2)
1119
+ # perform Shapiro-Wilk test for normality
1120
+ for i in (0, 1):
1121
+ _, pval = shapiro(samples[:, i])
1122
+ assert pval > 0.9
1123
+ # make sure samples are uncorrelated
1124
+ cov = np.cov(samples.transpose())
1125
+ assert np.abs(cov[0, 1]) < 1e-2
1126
+
1127
+
1128
+ class TestMultivariateNormalQMC:
1129
+
1130
+ def test_validations(self):
1131
+
1132
+ message = r"Dimension of `engine` must be consistent"
1133
+ with pytest.raises(ValueError, match=message):
1134
+ qmc.MultivariateNormalQMC([0], engine=qmc.Sobol(d=2))
1135
+
1136
+ message = r"Dimension of `engine` must be consistent"
1137
+ with pytest.raises(ValueError, match=message):
1138
+ qmc.MultivariateNormalQMC([0, 0, 0], engine=qmc.Sobol(d=4))
1139
+
1140
+ message = r"`engine` must be an instance of..."
1141
+ with pytest.raises(ValueError, match=message):
1142
+ qmc.MultivariateNormalQMC([0, 0], engine=np.random.default_rng())
1143
+
1144
+ message = r"Covariance matrix not PSD."
1145
+ with pytest.raises(ValueError, match=message):
1146
+ qmc.MultivariateNormalQMC([0, 0], [[1, 2], [2, 1]])
1147
+
1148
+ message = r"Covariance matrix is not symmetric."
1149
+ with pytest.raises(ValueError, match=message):
1150
+ qmc.MultivariateNormalQMC([0, 0], [[1, 0], [2, 1]])
1151
+
1152
+ message = r"Dimension mismatch between mean and covariance."
1153
+ with pytest.raises(ValueError, match=message):
1154
+ qmc.MultivariateNormalQMC([0], [[1, 0], [0, 1]])
1155
+
1156
+ def test_MultivariateNormalQMCNonPD(self):
1157
+ # try with non-pd but psd cov; should work
1158
+ engine = qmc.MultivariateNormalQMC(
1159
+ [0, 0, 0], [[1, 0, 1], [0, 1, 1], [1, 1, 2]],
1160
+ )
1161
+ assert engine._corr_matrix is not None
1162
+
1163
+ def test_MultivariateNormalQMC(self):
1164
+ # d = 1 scalar
1165
+ engine = qmc.MultivariateNormalQMC(mean=0, cov=5)
1166
+ samples = engine.random()
1167
+ assert_equal(samples.shape, (1, 1))
1168
+ samples = engine.random(n=5)
1169
+ assert_equal(samples.shape, (5, 1))
1170
+
1171
+ # d = 2 list
1172
+ engine = qmc.MultivariateNormalQMC(mean=[0, 1], cov=[[1, 0], [0, 1]])
1173
+ samples = engine.random()
1174
+ assert_equal(samples.shape, (1, 2))
1175
+ samples = engine.random(n=5)
1176
+ assert_equal(samples.shape, (5, 2))
1177
+
1178
+ # d = 3 np.array
1179
+ mean = np.array([0, 1, 2])
1180
+ cov = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
1181
+ engine = qmc.MultivariateNormalQMC(mean, cov)
1182
+ samples = engine.random()
1183
+ assert_equal(samples.shape, (1, 3))
1184
+ samples = engine.random(n=5)
1185
+ assert_equal(samples.shape, (5, 3))
1186
+
1187
+ def test_MultivariateNormalQMCInvTransform(self):
1188
+ # d = 1 scalar
1189
+ engine = qmc.MultivariateNormalQMC(mean=0, cov=5, inv_transform=True)
1190
+ samples = engine.random()
1191
+ assert_equal(samples.shape, (1, 1))
1192
+ samples = engine.random(n=5)
1193
+ assert_equal(samples.shape, (5, 1))
1194
+
1195
+ # d = 2 list
1196
+ engine = qmc.MultivariateNormalQMC(
1197
+ mean=[0, 1], cov=[[1, 0], [0, 1]], inv_transform=True,
1198
+ )
1199
+ samples = engine.random()
1200
+ assert_equal(samples.shape, (1, 2))
1201
+ samples = engine.random(n=5)
1202
+ assert_equal(samples.shape, (5, 2))
1203
+
1204
+ # d = 3 np.array
1205
+ mean = np.array([0, 1, 2])
1206
+ cov = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
1207
+ engine = qmc.MultivariateNormalQMC(mean, cov, inv_transform=True)
1208
+ samples = engine.random()
1209
+ assert_equal(samples.shape, (1, 3))
1210
+ samples = engine.random(n=5)
1211
+ assert_equal(samples.shape, (5, 3))
1212
+
1213
+ def test_MultivariateNormalQMCSeeded(self):
1214
+ # test even dimension
1215
+ rng = np.random.default_rng(180182791534511062935571481899241825000)
1216
+ a = rng.standard_normal((2, 2))
1217
+ A = a @ a.transpose() + np.diag(rng.random(2))
1218
+ engine = qmc.MultivariateNormalQMC(np.array([0, 0]), A,
1219
+ inv_transform=False, seed=rng)
1220
+ samples = engine.random(n=2)
1221
+ samples_expected = np.array([[-0.64419, -0.882413],
1222
+ [0.837199, 2.045301]])
1223
+ assert_allclose(samples, samples_expected, atol=1e-4)
1224
+
1225
+ # test odd dimension
1226
+ rng = np.random.default_rng(180182791534511062935571481899241825000)
1227
+ a = rng.standard_normal((3, 3))
1228
+ A = a @ a.transpose() + np.diag(rng.random(3))
1229
+ engine = qmc.MultivariateNormalQMC(np.array([0, 0, 0]), A,
1230
+ inv_transform=False, seed=rng)
1231
+ samples = engine.random(n=2)
1232
+ samples_expected = np.array([[-0.693853, -1.265338, -0.088024],
1233
+ [1.620193, 2.679222, 0.457343]])
1234
+ assert_allclose(samples, samples_expected, atol=1e-4)
1235
+
1236
+ def test_MultivariateNormalQMCSeededInvTransform(self):
1237
+ # test even dimension
1238
+ rng = np.random.default_rng(224125808928297329711992996940871155974)
1239
+ a = rng.standard_normal((2, 2))
1240
+ A = a @ a.transpose() + np.diag(rng.random(2))
1241
+ engine = qmc.MultivariateNormalQMC(
1242
+ np.array([0, 0]), A, seed=rng, inv_transform=True
1243
+ )
1244
+ samples = engine.random(n=2)
1245
+ samples_expected = np.array([[0.682171, -3.114233],
1246
+ [-0.098463, 0.668069]])
1247
+ assert_allclose(samples, samples_expected, atol=1e-4)
1248
+
1249
+ # test odd dimension
1250
+ rng = np.random.default_rng(224125808928297329711992996940871155974)
1251
+ a = rng.standard_normal((3, 3))
1252
+ A = a @ a.transpose() + np.diag(rng.random(3))
1253
+ engine = qmc.MultivariateNormalQMC(
1254
+ np.array([0, 0, 0]), A, seed=rng, inv_transform=True
1255
+ )
1256
+ samples = engine.random(n=2)
1257
+ samples_expected = np.array([[0.988061, -1.644089, -0.877035],
1258
+ [-1.771731, 1.096988, 2.024744]])
1259
+ assert_allclose(samples, samples_expected, atol=1e-4)
1260
+
1261
+ def test_MultivariateNormalQMCShapiro(self):
1262
+ # test the standard case
1263
+ seed = np.random.default_rng(188960007281846377164494575845971640)
1264
+ engine = qmc.MultivariateNormalQMC(
1265
+ mean=[0, 0], cov=[[1, 0], [0, 1]], seed=seed
1266
+ )
1267
+ samples = engine.random(n=256)
1268
+ assert all(np.abs(samples.mean(axis=0)) < 1e-2)
1269
+ assert all(np.abs(samples.std(axis=0) - 1) < 1e-2)
1270
+ # perform Shapiro-Wilk test for normality
1271
+ for i in (0, 1):
1272
+ _, pval = shapiro(samples[:, i])
1273
+ assert pval > 0.9
1274
+ # make sure samples are uncorrelated
1275
+ cov = np.cov(samples.transpose())
1276
+ assert np.abs(cov[0, 1]) < 1e-2
1277
+
1278
+ # test the correlated, non-zero mean case
1279
+ engine = qmc.MultivariateNormalQMC(
1280
+ mean=[1.0, 2.0], cov=[[1.5, 0.5], [0.5, 1.5]], seed=seed
1281
+ )
1282
+ samples = engine.random(n=256)
1283
+ assert all(np.abs(samples.mean(axis=0) - [1, 2]) < 1e-2)
1284
+ assert all(np.abs(samples.std(axis=0) - np.sqrt(1.5)) < 1e-2)
1285
+ # perform Shapiro-Wilk test for normality
1286
+ for i in (0, 1):
1287
+ _, pval = shapiro(samples[:, i])
1288
+ assert pval > 0.9
1289
+ # check covariance
1290
+ cov = np.cov(samples.transpose())
1291
+ assert np.abs(cov[0, 1] - 0.5) < 1e-2
1292
+
1293
+ def test_MultivariateNormalQMCShapiroInvTransform(self):
1294
+ # test the standard case
1295
+ seed = np.random.default_rng(200089821034563288698994840831440331329)
1296
+ engine = qmc.MultivariateNormalQMC(
1297
+ mean=[0, 0], cov=[[1, 0], [0, 1]], seed=seed, inv_transform=True
1298
+ )
1299
+ samples = engine.random(n=256)
1300
+ assert all(np.abs(samples.mean(axis=0)) < 1e-2)
1301
+ assert all(np.abs(samples.std(axis=0) - 1) < 1e-2)
1302
+ # perform Shapiro-Wilk test for normality
1303
+ for i in (0, 1):
1304
+ _, pval = shapiro(samples[:, i])
1305
+ assert pval > 0.9
1306
+ # make sure samples are uncorrelated
1307
+ cov = np.cov(samples.transpose())
1308
+ assert np.abs(cov[0, 1]) < 1e-2
1309
+
1310
+ # test the correlated, non-zero mean case
1311
+ engine = qmc.MultivariateNormalQMC(
1312
+ mean=[1.0, 2.0],
1313
+ cov=[[1.5, 0.5], [0.5, 1.5]],
1314
+ seed=seed,
1315
+ inv_transform=True,
1316
+ )
1317
+ samples = engine.random(n=256)
1318
+ assert all(np.abs(samples.mean(axis=0) - [1, 2]) < 1e-2)
1319
+ assert all(np.abs(samples.std(axis=0) - np.sqrt(1.5)) < 1e-2)
1320
+ # perform Shapiro-Wilk test for normality
1321
+ for i in (0, 1):
1322
+ _, pval = shapiro(samples[:, i])
1323
+ assert pval > 0.9
1324
+ # check covariance
1325
+ cov = np.cov(samples.transpose())
1326
+ assert np.abs(cov[0, 1] - 0.5) < 1e-2
1327
+
1328
+ def test_MultivariateNormalQMCDegenerate(self):
1329
+ # X, Y iid standard Normal and Z = X + Y, random vector (X, Y, Z)
1330
+ seed = np.random.default_rng(16320637417581448357869821654290448620)
1331
+ engine = qmc.MultivariateNormalQMC(
1332
+ mean=[0.0, 0.0, 0.0],
1333
+ cov=[[1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [1.0, 1.0, 2.0]],
1334
+ seed=seed,
1335
+ )
1336
+ samples = engine.random(n=512)
1337
+ assert all(np.abs(samples.mean(axis=0)) < 1e-2)
1338
+ assert np.abs(np.std(samples[:, 0]) - 1) < 1e-2
1339
+ assert np.abs(np.std(samples[:, 1]) - 1) < 1e-2
1340
+ assert np.abs(np.std(samples[:, 2]) - np.sqrt(2)) < 1e-2
1341
+ for i in (0, 1, 2):
1342
+ _, pval = shapiro(samples[:, i])
1343
+ assert pval > 0.8
1344
+ cov = np.cov(samples.transpose())
1345
+ assert np.abs(cov[0, 1]) < 1e-2
1346
+ assert np.abs(cov[0, 2] - 1) < 1e-2
1347
+ # check to see if X + Y = Z almost exactly
1348
+ assert all(np.abs(samples[:, 0] + samples[:, 1] - samples[:, 2])
1349
+ < 1e-5)
1350
+
1351
+
1352
+ class TestLloyd:
1353
+ def test_lloyd(self):
1354
+ # quite sensible seed as it can go up before going further down
1355
+ rng = np.random.RandomState(1809831)
1356
+ sample = rng.uniform(0, 1, size=(128, 2))
1357
+ base_l1 = _l1_norm(sample)
1358
+ base_l2 = l2_norm(sample)
1359
+
1360
+ for _ in range(4):
1361
+ sample_lloyd = _lloyd_centroidal_voronoi_tessellation(
1362
+ sample, maxiter=1,
1363
+ )
1364
+ curr_l1 = _l1_norm(sample_lloyd)
1365
+ curr_l2 = l2_norm(sample_lloyd)
1366
+
1367
+ # higher is better for the distance measures
1368
+ assert base_l1 < curr_l1
1369
+ assert base_l2 < curr_l2
1370
+
1371
+ base_l1 = curr_l1
1372
+ base_l2 = curr_l2
1373
+
1374
+ sample = sample_lloyd
1375
+
1376
+ def test_lloyd_non_mutating(self):
1377
+ """
1378
+ Verify that the input samples are not mutated in place and that they do
1379
+ not share memory with the output.
1380
+ """
1381
+ sample_orig = np.array([[0.1, 0.1],
1382
+ [0.1, 0.2],
1383
+ [0.2, 0.1],
1384
+ [0.2, 0.2]])
1385
+ sample_copy = sample_orig.copy()
1386
+ new_sample = _lloyd_centroidal_voronoi_tessellation(
1387
+ sample=sample_orig
1388
+ )
1389
+ assert_allclose(sample_orig, sample_copy)
1390
+ assert not np.may_share_memory(sample_orig, new_sample)
1391
+
1392
+ def test_lloyd_errors(self):
1393
+ with pytest.raises(ValueError, match=r"`sample` is not a 2D array"):
1394
+ sample = [0, 1, 0.5]
1395
+ _lloyd_centroidal_voronoi_tessellation(sample)
1396
+
1397
+ msg = r"`sample` dimension is not >= 2"
1398
+ with pytest.raises(ValueError, match=msg):
1399
+ sample = [[0], [0.4], [1]]
1400
+ _lloyd_centroidal_voronoi_tessellation(sample)
1401
+
1402
+ msg = r"`sample` is not in unit hypercube"
1403
+ with pytest.raises(ValueError, match=msg):
1404
+ sample = [[-1.1, 0], [0.1, 0.4], [1, 2]]
1405
+ _lloyd_centroidal_voronoi_tessellation(sample)
1406
+
1407
+
1408
+ # mindist
1409
+ def l2_norm(sample):
1410
+ return distance.pdist(sample).min()
parrot/lib/python3.10/site-packages/scipy/stats/tests/test_stats.py ADDED
The diff for this file is too large to render. See raw diff
 
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_cast_Short_ops.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _cast_Short {
18
+ using schema = at::Tensor (const at::Tensor &, bool);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_cast_Short")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_cast_Short(Tensor self, bool non_blocking=False) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self, bool non_blocking);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, bool non_blocking);
26
+ };
27
+
28
+ }} // namespace at::_ops
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_cufft_clear_plan_cache_native.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API void _cufft_clear_plan_cache(at::DeviceIndex device_index);
20
+ } // namespace native
21
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_tensor_storage_offsets_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _nested_tensor_storage_offsets {
18
+ using schema = at::Tensor (const at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_nested_tensor_storage_offsets")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_nested_tensor_storage_offsets(Tensor self) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
26
+ };
27
+
28
+ struct TORCH_API _nested_tensor_storage_offsets_out {
29
+ using schema = at::Tensor & (const at::Tensor &, at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_nested_tensor_storage_offsets")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_nested_tensor_storage_offsets.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)")
35
+ static at::Tensor & call(const at::Tensor & self, at::Tensor & out);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out);
37
+ };
38
+
39
+ }} // namespace at::_ops
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_to_sparse_csr_cuda_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API at::Tensor _to_sparse_csr(const at::Tensor & self, c10::optional<int64_t> dense_dim=c10::nullopt);
21
+
22
+ } // namespace cuda
23
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/bernoulli_ops.h ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API bernoulli {
18
+ using schema = at::Tensor (const at::Tensor &, c10::optional<at::Generator>);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bernoulli")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bernoulli(Tensor self, *, Generator? generator=None) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self, c10::optional<at::Generator> generator);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::optional<at::Generator> generator);
26
+ };
27
+
28
+ struct TORCH_API bernoulli_out {
29
+ using schema = at::Tensor & (const at::Tensor &, c10::optional<at::Generator>, at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bernoulli")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bernoulli.out(Tensor self, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!)")
35
+ static at::Tensor & call(const at::Tensor & self, c10::optional<at::Generator> generator, at::Tensor & out);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::optional<at::Generator> generator, at::Tensor & out);
37
+ };
38
+
39
+ struct TORCH_API bernoulli__Tensor {
40
+ using schema = at::Tensor & (at::Tensor &, const at::Tensor &, c10::optional<at::Generator>);
41
+ using ptr_schema = schema*;
42
+ // See Note [static constexpr char* members for windows NVCC]
43
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bernoulli_")
44
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor")
45
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bernoulli_.Tensor(Tensor(a!) self, Tensor p, *, Generator? generator=None) -> Tensor(a!)")
46
+ static at::Tensor & call(at::Tensor & self, const at::Tensor & p, c10::optional<at::Generator> generator);
47
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & p, c10::optional<at::Generator> generator);
48
+ };
49
+
50
+ struct TORCH_API bernoulli__float {
51
+ using schema = at::Tensor & (at::Tensor &, double, c10::optional<at::Generator>);
52
+ using ptr_schema = schema*;
53
+ // See Note [static constexpr char* members for windows NVCC]
54
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bernoulli_")
55
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "float")
56
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bernoulli_.float(Tensor(a!) self, float p=0.5, *, Generator? generator=None) -> Tensor(a!)")
57
+ static at::Tensor & call(at::Tensor & self, double p, c10::optional<at::Generator> generator);
58
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, double p, c10::optional<at::Generator> generator);
59
+ };
60
+
61
+ struct TORCH_API bernoulli_p {
62
+ using schema = at::Tensor (const at::Tensor &, double, c10::optional<at::Generator>);
63
+ using ptr_schema = schema*;
64
+ // See Note [static constexpr char* members for windows NVCC]
65
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bernoulli")
66
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "p")
67
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bernoulli.p(Tensor self, float p, *, Generator? generator=None) -> Tensor")
68
+ static at::Tensor call(const at::Tensor & self, double p, c10::optional<at::Generator> generator);
69
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, double p, c10::optional<at::Generator> generator);
70
+ };
71
+
72
+ struct TORCH_API bernoulli_Tensor_out {
73
+ using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, c10::optional<at::Generator>, at::Tensor &);
74
+ using ptr_schema = schema*;
75
+ // See Note [static constexpr char* members for windows NVCC]
76
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bernoulli")
77
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_out")
78
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bernoulli.Tensor_out(Tensor self, Tensor p, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!)")
79
+ static at::Tensor & call(const at::Tensor & self, const at::Tensor & p, c10::optional<at::Generator> generator, at::Tensor & out);
80
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & p, c10::optional<at::Generator> generator, at::Tensor & out);
81
+ };
82
+
83
+ struct TORCH_API bernoulli_Tensor {
84
+ using schema = at::Tensor (const at::Tensor &, const at::Tensor &, c10::optional<at::Generator>);
85
+ using ptr_schema = schema*;
86
+ // See Note [static constexpr char* members for windows NVCC]
87
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bernoulli")
88
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor")
89
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bernoulli.Tensor(Tensor self, Tensor p, *, Generator? generator=None) -> Tensor")
90
+ static at::Tensor call(const at::Tensor & self, const at::Tensor & p, c10::optional<at::Generator> generator);
91
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & p, c10::optional<at::Generator> generator);
92
+ };
93
+
94
+ struct TORCH_API bernoulli_float_out {
95
+ using schema = at::Tensor & (const at::Tensor &, double, c10::optional<at::Generator>, at::Tensor &);
96
+ using ptr_schema = schema*;
97
+ // See Note [static constexpr char* members for windows NVCC]
98
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bernoulli")
99
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "float_out")
100
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bernoulli.float_out(Tensor self, float p=0.5, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!)")
101
+ static at::Tensor & call(const at::Tensor & self, double p, c10::optional<at::Generator> generator, at::Tensor & out);
102
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, double p, c10::optional<at::Generator> generator, at::Tensor & out);
103
+ };
104
+
105
+ }} // namespace at::_ops
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/convolution_backward_overrideable.h ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/convolution_backward_overrideable_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::convolution_backward_overrideable(Tensor grad_output, Tensor input, Tensor weight, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias)
26
+ inline ::std::tuple<at::Tensor,at::Tensor,at::Tensor> convolution_backward_overrideable(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array<bool,3> output_mask) {
27
+ return at::_ops::convolution_backward_overrideable::call(grad_output, input, weight, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), transposed, c10::fromIntArrayRefSlow(output_padding), groups, output_mask);
28
+ }
29
+ namespace symint {
30
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
31
+ ::std::tuple<at::Tensor,at::Tensor,at::Tensor> convolution_backward_overrideable(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array<bool,3> output_mask) {
32
+ return at::_ops::convolution_backward_overrideable::call(grad_output, input, weight, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), transposed, c10::fromIntArrayRefSlow(output_padding), groups, output_mask);
33
+ }
34
+ }
35
+
36
+ // aten::convolution_backward_overrideable(Tensor grad_output, Tensor input, Tensor weight, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias)
37
+ inline ::std::tuple<at::Tensor,at::Tensor,at::Tensor> convolution_backward_overrideable_symint(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups, ::std::array<bool,3> output_mask) {
38
+ return at::_ops::convolution_backward_overrideable::call(grad_output, input, weight, stride, padding, dilation, transposed, output_padding, groups, output_mask);
39
+ }
40
+ namespace symint {
41
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
42
+ ::std::tuple<at::Tensor,at::Tensor,at::Tensor> convolution_backward_overrideable(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups, ::std::array<bool,3> output_mask) {
43
+ return at::_ops::convolution_backward_overrideable::call(grad_output, input, weight, stride, padding, dilation, transposed, output_padding, groups, output_mask);
44
+ }
45
+ }
46
+
47
+ // aten::convolution_backward_overrideable.out(Tensor grad_output, Tensor input, Tensor weight, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!))
48
+ inline ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> convolution_backward_overrideable_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array<bool,3> output_mask) {
49
+ return at::_ops::convolution_backward_overrideable_out::call(grad_output, input, weight, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), transposed, c10::fromIntArrayRefSlow(output_padding), groups, output_mask, out0, out1, out2);
50
+ }
51
+ namespace symint {
52
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
53
+ ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> convolution_backward_overrideable_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array<bool,3> output_mask) {
54
+ return at::_ops::convolution_backward_overrideable_out::call(grad_output, input, weight, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), transposed, c10::fromIntArrayRefSlow(output_padding), groups, output_mask, out0, out1, out2);
55
+ }
56
+ }
57
+
58
+ // aten::convolution_backward_overrideable.out(Tensor grad_output, Tensor input, Tensor weight, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!))
59
+ inline ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> convolution_backward_overrideable_outf(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array<bool,3> output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2) {
60
+ return at::_ops::convolution_backward_overrideable_out::call(grad_output, input, weight, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), transposed, c10::fromIntArrayRefSlow(output_padding), groups, output_mask, out0, out1, out2);
61
+ }
62
+ namespace symint {
63
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
64
+ ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> convolution_backward_overrideable_outf(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array<bool,3> output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2) {
65
+ return at::_ops::convolution_backward_overrideable_out::call(grad_output, input, weight, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), transposed, c10::fromIntArrayRefSlow(output_padding), groups, output_mask, out0, out1, out2);
66
+ }
67
+ }
68
+
69
+ // aten::convolution_backward_overrideable.out(Tensor grad_output, Tensor input, Tensor weight, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!))
70
+ inline ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> convolution_backward_overrideable_symint_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups, ::std::array<bool,3> output_mask) {
71
+ return at::_ops::convolution_backward_overrideable_out::call(grad_output, input, weight, stride, padding, dilation, transposed, output_padding, groups, output_mask, out0, out1, out2);
72
+ }
73
+ namespace symint {
74
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
75
+ ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> convolution_backward_overrideable_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups, ::std::array<bool,3> output_mask) {
76
+ return at::_ops::convolution_backward_overrideable_out::call(grad_output, input, weight, stride, padding, dilation, transposed, output_padding, groups, output_mask, out0, out1, out2);
77
+ }
78
+ }
79
+
80
+ // aten::convolution_backward_overrideable.out(Tensor grad_output, Tensor input, Tensor weight, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!))
81
+ inline ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> convolution_backward_overrideable_symint_outf(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups, ::std::array<bool,3> output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2) {
82
+ return at::_ops::convolution_backward_overrideable_out::call(grad_output, input, weight, stride, padding, dilation, transposed, output_padding, groups, output_mask, out0, out1, out2);
83
+ }
84
+ namespace symint {
85
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
86
+ ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> convolution_backward_overrideable_outf(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups, ::std::array<bool,3> output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2) {
87
+ return at::_ops::convolution_backward_overrideable_out::call(grad_output, input, weight, stride, padding, dilation, transposed, output_padding, groups, output_mask, out0, out1, out2);
88
+ }
89
+ }
90
+
91
+ }
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/fused_moving_avg_obs_fake_quant_ops.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API fused_moving_avg_obs_fake_quant {
18
+ using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, at::Tensor &, at::Tensor &, at::Tensor &, at::Tensor &, double, int64_t, int64_t, int64_t, bool, bool);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::fused_moving_avg_obs_fake_quant")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "fused_moving_avg_obs_fake_quant(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor(a!) running_min, Tensor(b!) running_max, Tensor(c!) scale, Tensor(d!) zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self, const at::Tensor & observer_on, const at::Tensor & fake_quant_on, at::Tensor & running_min, at::Tensor & running_max, at::Tensor & scale, at::Tensor & zero_point, double averaging_const, int64_t quant_min, int64_t quant_max, int64_t ch_axis, bool per_row_fake_quant, bool symmetric_quant);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & observer_on, const at::Tensor & fake_quant_on, at::Tensor & running_min, at::Tensor & running_max, at::Tensor & scale, at::Tensor & zero_point, double averaging_const, int64_t quant_min, int64_t quant_max, int64_t ch_axis, bool per_row_fake_quant, bool symmetric_quant);
26
+ };
27
+
28
+ }} // namespace at::_ops
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/hann_window.h ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/hann_window_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::hann_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
26
+ inline at::Tensor hann_window(int64_t window_length, at::TensorOptions options={}) {
27
+ return at::_ops::hann_window::call(window_length, optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt());
28
+ }
29
+ // aten::hann_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
30
+ inline at::Tensor hann_window(int64_t window_length, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory) {
31
+ return at::_ops::hann_window::call(window_length, dtype, layout, device, pin_memory);
32
+ }
33
+
34
+ // aten::hann_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
35
+ inline at::Tensor hann_window(int64_t window_length, bool periodic, at::TensorOptions options={}) {
36
+ return at::_ops::hann_window_periodic::call(window_length, periodic, optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt());
37
+ }
38
+ // aten::hann_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
39
+ inline at::Tensor hann_window(int64_t window_length, bool periodic, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory) {
40
+ return at::_ops::hann_window_periodic::call(window_length, periodic, dtype, layout, device, pin_memory);
41
+ }
42
+
43
+ // aten::hann_window.out(int window_length, *, Tensor(a!) out) -> Tensor(a!)
44
+ inline at::Tensor & hann_window_out(at::Tensor & out, int64_t window_length) {
45
+ return at::_ops::hann_window_out::call(window_length, out);
46
+ }
47
+ // aten::hann_window.out(int window_length, *, Tensor(a!) out) -> Tensor(a!)
48
+ inline at::Tensor & hann_window_outf(int64_t window_length, at::Tensor & out) {
49
+ return at::_ops::hann_window_out::call(window_length, out);
50
+ }
51
+
52
+ // aten::hann_window.periodic_out(int window_length, bool periodic, *, Tensor(a!) out) -> Tensor(a!)
53
+ inline at::Tensor & hann_window_out(at::Tensor & out, int64_t window_length, bool periodic) {
54
+ return at::_ops::hann_window_periodic_out::call(window_length, periodic, out);
55
+ }
56
+ // aten::hann_window.periodic_out(int window_length, bool periodic, *, Tensor(a!) out) -> Tensor(a!)
57
+ inline at::Tensor & hann_window_outf(int64_t window_length, bool periodic, at::Tensor & out) {
58
+ return at::_ops::hann_window_periodic_out::call(window_length, periodic, out);
59
+ }
60
+
61
+ }
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/is_signed.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/is_signed_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::is_signed(Tensor self) -> bool
26
+ inline bool __dispatch_is_signed(const at::Tensor & self) {
27
+ return at::_ops::is_signed::call(self);
28
+ }
29
+
30
+ }
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/leaky_relu_backward.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/leaky_relu_backward_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::leaky_relu_backward.grad_input(Tensor grad_output, Tensor self, Scalar negative_slope, bool self_is_result, *, Tensor(a!) grad_input) -> Tensor(a!)
26
+ inline at::Tensor & leaky_relu_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & negative_slope, bool self_is_result) {
27
+ return at::_ops::leaky_relu_backward_grad_input::call(grad_output, self, negative_slope, self_is_result, grad_input);
28
+ }
29
+ // aten::leaky_relu_backward.grad_input(Tensor grad_output, Tensor self, Scalar negative_slope, bool self_is_result, *, Tensor(a!) grad_input) -> Tensor(a!)
30
+ inline at::Tensor & leaky_relu_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & negative_slope, bool self_is_result, at::Tensor & grad_input) {
31
+ return at::_ops::leaky_relu_backward_grad_input::call(grad_output, self, negative_slope, self_is_result, grad_input);
32
+ }
33
+
34
+ // aten::leaky_relu_backward(Tensor grad_output, Tensor self, Scalar negative_slope, bool self_is_result) -> Tensor
35
+ inline at::Tensor leaky_relu_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & negative_slope, bool self_is_result) {
36
+ return at::_ops::leaky_relu_backward::call(grad_output, self, negative_slope, self_is_result);
37
+ }
38
+
39
+ }
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/rnn_relu_compositeimplicitautograd_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeimplicitautograd {
19
+
20
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor> rnn_relu(const at::Tensor & input, const at::Tensor & hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional, bool batch_first);
21
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor> rnn_relu(const at::Tensor & data, const at::Tensor & batch_sizes, const at::Tensor & hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional);
22
+
23
+ } // namespace compositeimplicitautograd
24
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/select_scatter_native.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor & select_scatter_out_symint(const at::Tensor & self, const at::Tensor & src, int64_t dim, c10::SymInt index, at::Tensor & out);
20
+ TORCH_API at::Tensor select_scatter_symint(const at::Tensor & self, const at::Tensor & src, int64_t dim, c10::SymInt index);
21
+ } // namespace native
22
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/sym_storage_offset_compositeimplicitautograd_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeimplicitautograd {
19
+
20
+ TORCH_API c10::SymInt sym_storage_offset(const at::Tensor & self);
21
+
22
+ } // namespace compositeimplicitautograd
23
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/trapz.h ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/trapz_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::trapz.x(Tensor y, Tensor x, *, int dim=-1) -> Tensor
26
+ inline at::Tensor trapz(const at::Tensor & y, const at::Tensor & x, int64_t dim=-1) {
27
+ return at::_ops::trapz_x::call(y, x, dim);
28
+ }
29
+
30
+ // aten::trapz.dx(Tensor y, *, float dx=1, int dim=-1) -> Tensor
31
+ inline at::Tensor trapz(const at::Tensor & y, double dx=1, int64_t dim=-1) {
32
+ return at::_ops::trapz_dx::call(y, dx, dim);
33
+ }
34
+
35
+ }
vllm/lib/python3.10/site-packages/ray/cloudpickle/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.34 kB). View file
 
vllm/lib/python3.10/site-packages/ray/cloudpickle/__pycache__/cloudpickle.cpython-310.pyc ADDED
Binary file (36.8 kB). View file
 
vllm/lib/python3.10/site-packages/ray/cloudpickle/__pycache__/compat.cpython-310.pyc ADDED
Binary file (705 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/cloudpickle/py_pickle.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pickle import (
2
+ _Pickler,
3
+ _Unpickler as Unpickler,
4
+ _loads as loads,
5
+ _load as load,
6
+ PickleError,
7
+ PicklingError,
8
+ UnpicklingError,
9
+ HIGHEST_PROTOCOL,
10
+ )
11
+
12
+ __all__ = [
13
+ "PickleError",
14
+ "PicklingError",
15
+ "UnpicklingError",
16
+ "Pickler",
17
+ "Unpickler",
18
+ "load",
19
+ "loads",
20
+ "HIGHEST_PROTOCOL",
21
+ ]
22
+
23
+
24
+ class Pickler(_Pickler):
25
+ def __init__(self, file, protocol=None, *, fix_imports=True, buffer_callback=None):
26
+ super().__init__(
27
+ file, protocol, fix_imports=fix_imports, buffer_callback=buffer_callback
28
+ )
29
+ # avoid being overrided by cloudpickle
30
+ self.dispatch = _Pickler.dispatch.copy()
vllm/lib/python3.10/site-packages/ray/internal/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from ray._private.internal_api import free
2
+
3
+ __all__ = ["free"]
vllm/lib/python3.10/site-packages/ray/internal/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (238 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/scripts/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/ray/scripts/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (161 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/scripts/__pycache__/scripts.cpython-310.pyc ADDED
Binary file (54.1 kB). View file
 
vllm/lib/python3.10/site-packages/ray/scripts/scripts.py ADDED
@@ -0,0 +1,2672 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import json
3
+ import logging
4
+ import os
5
+ import platform
6
+ import signal
7
+ import subprocess
8
+ import sys
9
+ import time
10
+ import urllib
11
+ import urllib.parse
12
+ import warnings
13
+ import shutil
14
+ from datetime import datetime
15
+ from typing import Optional, Set, List, Tuple
16
+ from ray.dashboard.modules.metrics import install_and_start_prometheus
17
+ from ray.util.check_open_ports import check_open_ports
18
+ import requests
19
+
20
+ import click
21
+ import psutil
22
+ import yaml
23
+
24
+ import ray
25
+ import ray._private.ray_constants as ray_constants
26
+ import ray._private.services as services
27
+ from ray._private.utils import (
28
+ check_ray_client_dependencies_installed,
29
+ parse_resources_json,
30
+ parse_node_labels_json,
31
+ )
32
+ from ray._private.internal_api import memory_summary
33
+ from ray._private.storage import _load_class
34
+ from ray._private.usage import usage_lib
35
+ from ray.autoscaler._private.cli_logger import add_click_logging_options, cf, cli_logger
36
+ from ray.autoscaler._private.commands import (
37
+ RUN_ENV_TYPES,
38
+ attach_cluster,
39
+ create_or_update_cluster,
40
+ debug_status,
41
+ exec_cluster,
42
+ get_cluster_dump_archive,
43
+ get_head_node_ip,
44
+ get_local_dump_archive,
45
+ get_worker_node_ips,
46
+ kill_node,
47
+ monitor_cluster,
48
+ rsync,
49
+ teardown_cluster,
50
+ )
51
+ from ray.autoscaler._private.constants import RAY_PROCESSES
52
+ from ray.autoscaler._private.fake_multi_node.node_provider import FAKE_HEAD_NODE_ID
53
+ from ray.util.annotations import PublicAPI
54
+ from ray.core.generated import autoscaler_pb2
55
+
56
+
57
+ logger = logging.getLogger(__name__)
58
+
59
+
60
+ def _check_ray_version(gcs_client):
61
+ import ray._private.usage.usage_lib as ray_usage_lib
62
+
63
+ cluster_metadata = ray_usage_lib.get_cluster_metadata(gcs_client)
64
+ if cluster_metadata and cluster_metadata["ray_version"] != ray.__version__:
65
+ raise RuntimeError(
66
+ "Ray version mismatch: cluster has Ray version "
67
+ f'{cluster_metadata["ray_version"]} '
68
+ f"but local Ray version is {ray.__version__}"
69
+ )
70
+
71
+
72
+ @click.group()
73
+ @click.option(
74
+ "--logging-level",
75
+ required=False,
76
+ default=ray_constants.LOGGER_LEVEL,
77
+ type=str,
78
+ help=ray_constants.LOGGER_LEVEL_HELP,
79
+ )
80
+ @click.option(
81
+ "--logging-format",
82
+ required=False,
83
+ default=ray_constants.LOGGER_FORMAT,
84
+ type=str,
85
+ help=ray_constants.LOGGER_FORMAT_HELP,
86
+ )
87
+ @click.version_option()
88
+ def cli(logging_level, logging_format):
89
+ level = logging.getLevelName(logging_level.upper())
90
+ ray._private.ray_logging.setup_logger(level, logging_format)
91
+ cli_logger.set_format(format_tmpl=logging_format)
92
+
93
+
94
+ @click.command()
95
+ @click.argument("cluster_config_file", required=True, type=str)
96
+ @click.option(
97
+ "--cluster-name",
98
+ "-n",
99
+ required=False,
100
+ type=str,
101
+ help="Override the configured cluster name.",
102
+ )
103
+ @click.option(
104
+ "--port",
105
+ "-p",
106
+ required=False,
107
+ type=int,
108
+ default=ray_constants.DEFAULT_DASHBOARD_PORT,
109
+ help="The local port to forward to the dashboard",
110
+ )
111
+ @click.option(
112
+ "--remote-port",
113
+ required=False,
114
+ type=int,
115
+ default=ray_constants.DEFAULT_DASHBOARD_PORT,
116
+ help="The remote port your dashboard runs on",
117
+ )
118
+ @click.option(
119
+ "--no-config-cache",
120
+ is_flag=True,
121
+ default=False,
122
+ help="Disable the local cluster config cache.",
123
+ )
124
+ @PublicAPI
125
+ def dashboard(cluster_config_file, cluster_name, port, remote_port, no_config_cache):
126
+ """Port-forward a Ray cluster's dashboard to the local machine."""
127
+ # Sleeping in a loop is preferable to `sleep infinity` because the latter
128
+ # only works on linux.
129
+ # Find the first open port sequentially from `remote_port`.
130
+ try:
131
+ port_forward = [
132
+ (port, remote_port),
133
+ ]
134
+ click.echo(
135
+ "Attempting to establish dashboard locally at"
136
+ " http://localhost:{}/ connected to"
137
+ " remote port {}".format(port, remote_port)
138
+ )
139
+ # We want to probe with a no-op that returns quickly to avoid
140
+ # exceptions caused by network errors.
141
+ exec_cluster(
142
+ cluster_config_file,
143
+ override_cluster_name=cluster_name,
144
+ port_forward=port_forward,
145
+ no_config_cache=no_config_cache,
146
+ )
147
+ click.echo("Successfully established connection.")
148
+ except Exception as e:
149
+ raise click.ClickException(
150
+ "Failed to forward dashboard from remote port {1} to local port "
151
+ "{0}. There are a couple possibilities: \n 1. The remote port is "
152
+ "incorrectly specified \n 2. The local port {0} is already in "
153
+ "use.\n The exception is: {2}".format(port, remote_port, e)
154
+ ) from None
155
+
156
+
157
+ def continue_debug_session(live_jobs: Set[str]):
158
+ """Continue active debugging session.
159
+
160
+ This function will connect 'ray debug' to the right debugger
161
+ when a user is stepping between Ray tasks.
162
+ """
163
+ active_sessions = ray.experimental.internal_kv._internal_kv_list(
164
+ "RAY_PDB_", namespace=ray_constants.KV_NAMESPACE_PDB
165
+ )
166
+
167
+ for active_session in active_sessions:
168
+ if active_session.startswith(b"RAY_PDB_CONTINUE"):
169
+ # Check to see that the relevant job is still alive.
170
+ data = ray.experimental.internal_kv._internal_kv_get(
171
+ active_session, namespace=ray_constants.KV_NAMESPACE_PDB
172
+ )
173
+ if json.loads(data)["job_id"] not in live_jobs:
174
+ ray.experimental.internal_kv._internal_kv_del(
175
+ active_session, namespace=ray_constants.KV_NAMESPACE_PDB
176
+ )
177
+ continue
178
+
179
+ print("Continuing pdb session in different process...")
180
+ key = b"RAY_PDB_" + active_session[len("RAY_PDB_CONTINUE_") :]
181
+ while True:
182
+ data = ray.experimental.internal_kv._internal_kv_get(
183
+ key, namespace=ray_constants.KV_NAMESPACE_PDB
184
+ )
185
+ if data:
186
+ session = json.loads(data)
187
+ if "exit_debugger" in session or session["job_id"] not in live_jobs:
188
+ ray.experimental.internal_kv._internal_kv_del(
189
+ key, namespace=ray_constants.KV_NAMESPACE_PDB
190
+ )
191
+ return
192
+ host, port = session["pdb_address"].split(":")
193
+ ray.util.rpdb._connect_pdb_client(host, int(port))
194
+ ray.experimental.internal_kv._internal_kv_del(
195
+ key, namespace=ray_constants.KV_NAMESPACE_PDB
196
+ )
197
+ continue_debug_session(live_jobs)
198
+ return
199
+ time.sleep(1.0)
200
+
201
+
202
+ def none_to_empty(s):
203
+ if s is None:
204
+ return ""
205
+ return s
206
+
207
+
208
+ def format_table(table):
209
+ """Format a table as a list of lines with aligned columns."""
210
+ result = []
211
+ col_width = [max(len(x) for x in col) for col in zip(*table)]
212
+ for line in table:
213
+ result.append(
214
+ " | ".join("{0:{1}}".format(x, col_width[i]) for i, x in enumerate(line))
215
+ )
216
+ return result
217
+
218
+
219
+ @cli.command()
220
+ @click.option(
221
+ "--address", required=False, type=str, help="Override the address to connect to."
222
+ )
223
+ @click.option(
224
+ "-v",
225
+ "--verbose",
226
+ required=False,
227
+ is_flag=True,
228
+ help="Shows additional fields in breakpoint selection page.",
229
+ )
230
+ def debug(address: str, verbose: bool):
231
+ """Show all active breakpoints and exceptions in the Ray debugger."""
232
+ address = services.canonicalize_bootstrap_address_or_die(address)
233
+ logger.info(f"Connecting to Ray instance at {address}.")
234
+ ray.init(address=address, log_to_driver=False)
235
+ while True:
236
+ # Used to filter out and clean up entries from dead jobs.
237
+ live_jobs = {
238
+ job["JobID"] for job in ray._private.state.jobs() if not job["IsDead"]
239
+ }
240
+ continue_debug_session(live_jobs)
241
+
242
+ active_sessions = ray.experimental.internal_kv._internal_kv_list(
243
+ "RAY_PDB_", namespace=ray_constants.KV_NAMESPACE_PDB
244
+ )
245
+ print("Active breakpoints:")
246
+ sessions_data = []
247
+ for active_session in active_sessions:
248
+ data = json.loads(
249
+ ray.experimental.internal_kv._internal_kv_get(
250
+ active_session, namespace=ray_constants.KV_NAMESPACE_PDB
251
+ )
252
+ )
253
+ # Check that the relevant job is alive, else clean up the entry.
254
+ if data["job_id"] in live_jobs:
255
+ sessions_data.append(data)
256
+ else:
257
+ ray.experimental.internal_kv._internal_kv_del(
258
+ active_session, namespace=ray_constants.KV_NAMESPACE_PDB
259
+ )
260
+ sessions_data = sorted(
261
+ sessions_data, key=lambda data: data["timestamp"], reverse=True
262
+ )
263
+ if verbose:
264
+ table = [
265
+ [
266
+ "index",
267
+ "timestamp",
268
+ "Ray task",
269
+ "filename:lineno",
270
+ "Task ID",
271
+ "Worker ID",
272
+ "Actor ID",
273
+ "Node ID",
274
+ ]
275
+ ]
276
+ for i, data in enumerate(sessions_data):
277
+ date = datetime.utcfromtimestamp(data["timestamp"]).strftime(
278
+ "%Y-%m-%d %H:%M:%S"
279
+ )
280
+ table.append(
281
+ [
282
+ str(i),
283
+ date,
284
+ data["proctitle"],
285
+ data["filename"] + ":" + str(data["lineno"]),
286
+ data["task_id"],
287
+ data["worker_id"],
288
+ none_to_empty(data["actor_id"]),
289
+ data["node_id"],
290
+ ]
291
+ )
292
+ else:
293
+ # Non verbose mode: no IDs.
294
+ table = [["index", "timestamp", "Ray task", "filename:lineno"]]
295
+ for i, data in enumerate(sessions_data):
296
+ date = datetime.utcfromtimestamp(data["timestamp"]).strftime(
297
+ "%Y-%m-%d %H:%M:%S"
298
+ )
299
+ table.append(
300
+ [
301
+ str(i),
302
+ date,
303
+ data["proctitle"],
304
+ data["filename"] + ":" + str(data["lineno"]),
305
+ ]
306
+ )
307
+ for i, line in enumerate(format_table(table)):
308
+ print(line)
309
+ if i >= 1 and not sessions_data[i - 1]["traceback"].startswith(
310
+ "NoneType: None"
311
+ ):
312
+ print(sessions_data[i - 1]["traceback"])
313
+ inp = input("Enter breakpoint index or press enter to refresh: ")
314
+ if inp == "":
315
+ print()
316
+ continue
317
+ else:
318
+ index = int(inp)
319
+ session = json.loads(
320
+ ray.experimental.internal_kv._internal_kv_get(
321
+ active_sessions[index], namespace=ray_constants.KV_NAMESPACE_PDB
322
+ )
323
+ )
324
+ host, port = session["pdb_address"].split(":")
325
+ ray.util.rpdb._connect_pdb_client(host, int(port))
326
+
327
+
328
+ @cli.command()
329
+ @click.option(
330
+ "--node-ip-address", required=False, type=str, help="the IP address of this node"
331
+ )
332
+ @click.option("--address", required=False, type=str, help="the address to use for Ray")
333
+ @click.option(
334
+ "--port",
335
+ type=int,
336
+ required=False,
337
+ help=f"the port of the head ray process. If not provided, defaults to "
338
+ f"{ray_constants.DEFAULT_PORT}; if port is set to 0, we will"
339
+ f" allocate an available port.",
340
+ )
341
+ @click.option(
342
+ "--node-name",
343
+ required=False,
344
+ hidden=True,
345
+ type=str,
346
+ help="the user-provided identifier or name for this node. "
347
+ "Defaults to the node's ip_address",
348
+ )
349
+ @click.option(
350
+ "--redis-password",
351
+ required=False,
352
+ hidden=True,
353
+ type=str,
354
+ default=ray_constants.REDIS_DEFAULT_PASSWORD,
355
+ help="If provided, secure Redis ports with this password",
356
+ )
357
+ @click.option(
358
+ "--redis-shard-ports",
359
+ required=False,
360
+ hidden=True,
361
+ type=str,
362
+ help="the port to use for the Redis shards other than the primary Redis shard",
363
+ )
364
+ @click.option(
365
+ "--object-manager-port",
366
+ required=False,
367
+ type=int,
368
+ help="the port to use for starting the object manager",
369
+ )
370
+ @click.option(
371
+ "--node-manager-port",
372
+ required=False,
373
+ type=int,
374
+ default=0,
375
+ help="the port to use for starting the node manager",
376
+ )
377
+ @click.option(
378
+ "--gcs-server-port",
379
+ required=False,
380
+ type=int,
381
+ help="Port number for the GCS server.",
382
+ )
383
+ @click.option(
384
+ "--min-worker-port",
385
+ required=False,
386
+ type=int,
387
+ default=10002,
388
+ help="the lowest port number that workers will bind on. If not set, "
389
+ "random ports will be chosen.",
390
+ )
391
+ @click.option(
392
+ "--max-worker-port",
393
+ required=False,
394
+ type=int,
395
+ default=19999,
396
+ help="the highest port number that workers will bind on. If set, "
397
+ "'--min-worker-port' must also be set.",
398
+ )
399
+ @click.option(
400
+ "--worker-port-list",
401
+ required=False,
402
+ help="a comma-separated list of open ports for workers to bind on. "
403
+ "Overrides '--min-worker-port' and '--max-worker-port'.",
404
+ )
405
+ @click.option(
406
+ "--ray-client-server-port",
407
+ required=False,
408
+ type=int,
409
+ default=None,
410
+ help="the port number the ray client server binds on, default to 10001, "
411
+ "or None if ray[client] is not installed.",
412
+ )
413
+ @click.option(
414
+ "--memory",
415
+ required=False,
416
+ hidden=True,
417
+ type=int,
418
+ help="The amount of memory (in bytes) to make available to workers. "
419
+ "By default, this is set to the available memory on the node.",
420
+ )
421
+ @click.option(
422
+ "--object-store-memory",
423
+ required=False,
424
+ type=int,
425
+ help="The amount of memory (in bytes) to start the object store with. "
426
+ "By default, this is 30% (ray_constants.DEFAULT_OBJECT_STORE_MEMORY_PROPORTION) "
427
+ "of available system memory capped by "
428
+ "the shm size and 200G (ray_constants.DEFAULT_OBJECT_STORE_MAX_MEMORY_BYTES) "
429
+ "but can be set higher.",
430
+ )
431
+ @click.option(
432
+ "--redis-max-memory",
433
+ required=False,
434
+ hidden=True,
435
+ type=int,
436
+ help="The max amount of memory (in bytes) to allow redis to use. Once the "
437
+ "limit is exceeded, redis will start LRU eviction of entries. This only "
438
+ "applies to the sharded redis tables (task, object, and profile tables). "
439
+ "By default this is capped at 10GB but can be set higher.",
440
+ )
441
+ @click.option(
442
+ "--num-cpus", required=False, type=int, help="the number of CPUs on this node"
443
+ )
444
+ @click.option(
445
+ "--num-gpus", required=False, type=int, help="the number of GPUs on this node"
446
+ )
447
+ @click.option(
448
+ "--resources",
449
+ required=False,
450
+ default="{}",
451
+ type=str,
452
+ help="A JSON serialized dictionary mapping resource name to resource quantity."
453
+ + (
454
+ r"""
455
+
456
+ Windows command prompt users must ensure to double quote command line arguments. Because
457
+ JSON requires the use of double quotes you must escape these arguments as well, for
458
+ example:
459
+
460
+ ray start --head --resources="{\"special_hardware\":1, \"custom_label\":1}"
461
+
462
+ Windows powershell users need additional escaping:
463
+
464
+ ray start --head --resources="{\""special_hardware\"":1, \""custom_label\"":1}"
465
+ """
466
+ if platform.system() == "Windows"
467
+ else ""
468
+ ),
469
+ )
470
+ @click.option(
471
+ "--head",
472
+ is_flag=True,
473
+ default=False,
474
+ help="provide this argument for the head node",
475
+ )
476
+ @click.option(
477
+ "--include-dashboard",
478
+ default=None,
479
+ type=bool,
480
+ help="provide this argument to start the Ray dashboard GUI",
481
+ )
482
+ @click.option(
483
+ "--dashboard-host",
484
+ required=False,
485
+ default=ray_constants.DEFAULT_DASHBOARD_IP,
486
+ help="the host to bind the dashboard server to, either localhost "
487
+ "(127.0.0.1) or 0.0.0.0 (available from all interfaces). By default, this "
488
+ "is 127.0.0.1",
489
+ )
490
+ @click.option(
491
+ "--dashboard-port",
492
+ required=False,
493
+ type=int,
494
+ default=ray_constants.DEFAULT_DASHBOARD_PORT,
495
+ help="the port to bind the dashboard server to--defaults to {}".format(
496
+ ray_constants.DEFAULT_DASHBOARD_PORT
497
+ ),
498
+ )
499
+ @click.option(
500
+ "--dashboard-agent-listen-port",
501
+ type=int,
502
+ default=ray_constants.DEFAULT_DASHBOARD_AGENT_LISTEN_PORT,
503
+ help="the port for dashboard agents to listen for http on.",
504
+ )
505
+ @click.option(
506
+ "--dashboard-agent-grpc-port",
507
+ type=int,
508
+ default=None,
509
+ help="the port for dashboard agents to listen for grpc on.",
510
+ )
511
+ @click.option(
512
+ "--dashboard-grpc-port",
513
+ type=int,
514
+ default=None,
515
+ help="The port for the dashboard head to listen for grpc on.",
516
+ )
517
+ @click.option(
518
+ "--runtime-env-agent-port",
519
+ type=int,
520
+ default=None,
521
+ help="The port for the runtime enviroment agents to listen for http on.",
522
+ )
523
+ @click.option(
524
+ "--block",
525
+ is_flag=True,
526
+ default=False,
527
+ help="provide this argument to block forever in this command",
528
+ )
529
+ @click.option(
530
+ "--plasma-directory",
531
+ required=False,
532
+ type=str,
533
+ help="object store directory for memory mapped files",
534
+ )
535
+ @click.option(
536
+ "--autoscaling-config",
537
+ required=False,
538
+ type=str,
539
+ help="the file that contains the autoscaling config",
540
+ )
541
+ @click.option(
542
+ "--no-redirect-output",
543
+ is_flag=True,
544
+ default=False,
545
+ help="do not redirect non-worker stdout and stderr to files",
546
+ )
547
+ @click.option(
548
+ "--plasma-store-socket-name",
549
+ default=None,
550
+ help="manually specify the socket name of the plasma store",
551
+ )
552
+ @click.option(
553
+ "--raylet-socket-name",
554
+ default=None,
555
+ help="manually specify the socket path of the raylet process",
556
+ )
557
+ @click.option(
558
+ "--temp-dir",
559
+ default=None,
560
+ help="manually specify the root temporary dir of the Ray process, only "
561
+ "works when --head is specified",
562
+ )
563
+ @click.option(
564
+ "--storage",
565
+ default=None,
566
+ help="the persistent storage URI for the cluster. Experimental.",
567
+ )
568
+ @click.option(
569
+ "--system-config",
570
+ default=None,
571
+ hidden=True,
572
+ type=json.loads,
573
+ help="Override system configuration defaults.",
574
+ )
575
+ @click.option(
576
+ "--enable-object-reconstruction",
577
+ is_flag=True,
578
+ default=False,
579
+ hidden=True,
580
+ help="Specify whether object reconstruction will be used for this cluster.",
581
+ )
582
+ @click.option(
583
+ "--metrics-export-port",
584
+ type=int,
585
+ default=None,
586
+ help="the port to use to expose Ray metrics through a Prometheus endpoint.",
587
+ )
588
+ @click.option(
589
+ "--no-monitor",
590
+ is_flag=True,
591
+ hidden=True,
592
+ default=False,
593
+ help="If True, the ray autoscaler monitor for this cluster will not be started.",
594
+ )
595
+ @click.option(
596
+ "--tracing-startup-hook",
597
+ type=str,
598
+ hidden=True,
599
+ default=None,
600
+ help="The function that sets up tracing with a tracing provider, remote "
601
+ "span processor, and additional instruments. See docs.ray.io/tracing.html "
602
+ "for more info.",
603
+ )
604
+ @click.option(
605
+ "--ray-debugger-external",
606
+ is_flag=True,
607
+ default=False,
608
+ help="Make the Ray debugger available externally to the node. This is only "
609
+ "safe to activate if the node is behind a firewall.",
610
+ )
611
+ @click.option(
612
+ "--disable-usage-stats",
613
+ is_flag=True,
614
+ default=False,
615
+ help="If True, the usage stats collection will be disabled.",
616
+ )
617
+ @click.option(
618
+ "--labels",
619
+ required=False,
620
+ hidden=True,
621
+ default="{}",
622
+ type=str,
623
+ help="a JSON serialized dictionary mapping label name to label value.",
624
+ )
625
+ @add_click_logging_options
626
+ @PublicAPI
627
+ def start(
628
+ node_ip_address,
629
+ address,
630
+ port,
631
+ node_name,
632
+ redis_password,
633
+ redis_shard_ports,
634
+ object_manager_port,
635
+ node_manager_port,
636
+ gcs_server_port,
637
+ min_worker_port,
638
+ max_worker_port,
639
+ worker_port_list,
640
+ ray_client_server_port,
641
+ memory,
642
+ object_store_memory,
643
+ redis_max_memory,
644
+ num_cpus,
645
+ num_gpus,
646
+ resources,
647
+ head,
648
+ include_dashboard,
649
+ dashboard_host,
650
+ dashboard_port,
651
+ dashboard_agent_listen_port,
652
+ dashboard_agent_grpc_port,
653
+ dashboard_grpc_port,
654
+ runtime_env_agent_port,
655
+ block,
656
+ plasma_directory,
657
+ autoscaling_config,
658
+ no_redirect_output,
659
+ plasma_store_socket_name,
660
+ raylet_socket_name,
661
+ temp_dir,
662
+ storage,
663
+ system_config,
664
+ enable_object_reconstruction,
665
+ metrics_export_port,
666
+ no_monitor,
667
+ tracing_startup_hook,
668
+ ray_debugger_external,
669
+ disable_usage_stats,
670
+ labels,
671
+ ):
672
+ """Start Ray processes manually on the local machine."""
673
+
674
+ if gcs_server_port is not None:
675
+ cli_logger.error(
676
+ "`{}` is deprecated and ignored. Use {} to specify "
677
+ "GCS server port on head node.",
678
+ cf.bold("--gcs-server-port"),
679
+ cf.bold("--port"),
680
+ )
681
+ # Whether the original arguments include node_ip_address.
682
+ include_node_ip_address = False
683
+ if node_ip_address is not None:
684
+ include_node_ip_address = True
685
+ node_ip_address = services.resolve_ip_for_localhost(node_ip_address)
686
+
687
+ resources = parse_resources_json(resources, cli_logger, cf)
688
+ labels_dict = parse_node_labels_json(labels, cli_logger, cf)
689
+
690
+ if plasma_store_socket_name is not None:
691
+ warnings.warn(
692
+ "plasma_store_socket_name is deprecated and will be removed. You are not "
693
+ "supposed to specify this parameter as it's internal.",
694
+ DeprecationWarning,
695
+ stacklevel=2,
696
+ )
697
+ if raylet_socket_name is not None:
698
+ warnings.warn(
699
+ "raylet_socket_name is deprecated and will be removed. You are not "
700
+ "supposed to specify this parameter as it's internal.",
701
+ DeprecationWarning,
702
+ stacklevel=2,
703
+ )
704
+ if temp_dir and not head:
705
+ cli_logger.warning(
706
+ f"`--temp-dir={temp_dir}` option will be ignored. "
707
+ "`--head` is a required flag to use `--temp-dir`. "
708
+ "temp_dir is only configurable from a head node. "
709
+ "All the worker nodes will use the same temp_dir as a head node. "
710
+ )
711
+ temp_dir = None
712
+
713
+ redirect_output = None if not no_redirect_output else True
714
+
715
+ # no client, no port -> ok
716
+ # no port, has client -> default to 10001
717
+ # has port, no client -> value error
718
+ # has port, has client -> ok, check port validity
719
+ has_ray_client = check_ray_client_dependencies_installed()
720
+ if has_ray_client and ray_client_server_port is None:
721
+ ray_client_server_port = 10001
722
+
723
+ ray_params = ray._private.parameter.RayParams(
724
+ node_ip_address=node_ip_address,
725
+ node_name=node_name if node_name else node_ip_address,
726
+ min_worker_port=min_worker_port,
727
+ max_worker_port=max_worker_port,
728
+ worker_port_list=worker_port_list,
729
+ ray_client_server_port=ray_client_server_port,
730
+ object_manager_port=object_manager_port,
731
+ node_manager_port=node_manager_port,
732
+ memory=memory,
733
+ object_store_memory=object_store_memory,
734
+ redis_password=redis_password,
735
+ redirect_output=redirect_output,
736
+ num_cpus=num_cpus,
737
+ num_gpus=num_gpus,
738
+ resources=resources,
739
+ labels=labels_dict,
740
+ autoscaling_config=autoscaling_config,
741
+ plasma_directory=plasma_directory,
742
+ huge_pages=False,
743
+ plasma_store_socket_name=plasma_store_socket_name,
744
+ raylet_socket_name=raylet_socket_name,
745
+ temp_dir=temp_dir,
746
+ storage=storage,
747
+ include_dashboard=include_dashboard,
748
+ dashboard_host=dashboard_host,
749
+ dashboard_port=dashboard_port,
750
+ dashboard_agent_listen_port=dashboard_agent_listen_port,
751
+ metrics_agent_port=dashboard_agent_grpc_port,
752
+ dashboard_grpc_port=dashboard_grpc_port,
753
+ runtime_env_agent_port=runtime_env_agent_port,
754
+ _system_config=system_config,
755
+ enable_object_reconstruction=enable_object_reconstruction,
756
+ metrics_export_port=metrics_export_port,
757
+ no_monitor=no_monitor,
758
+ tracing_startup_hook=tracing_startup_hook,
759
+ ray_debugger_external=ray_debugger_external,
760
+ )
761
+
762
+ if ray_constants.RAY_START_HOOK in os.environ:
763
+ _load_class(os.environ[ray_constants.RAY_START_HOOK])(ray_params, head)
764
+
765
+ if head:
766
+ # Start head node.
767
+
768
+ if disable_usage_stats:
769
+ usage_lib.set_usage_stats_enabled_via_env_var(False)
770
+ usage_lib.show_usage_stats_prompt(cli=True)
771
+ cli_logger.newline()
772
+
773
+ if port is None:
774
+ port = ray_constants.DEFAULT_PORT
775
+
776
+ # Set bootstrap port.
777
+ assert ray_params.redis_port is None
778
+ assert ray_params.gcs_server_port is None
779
+ ray_params.gcs_server_port = port
780
+
781
+ if os.environ.get("RAY_FAKE_CLUSTER"):
782
+ ray_params.env_vars = {
783
+ "RAY_OVERRIDE_NODE_ID_FOR_TESTING": FAKE_HEAD_NODE_ID
784
+ }
785
+
786
+ num_redis_shards = None
787
+ # Start Ray on the head node.
788
+ if redis_shard_ports is not None and address is None:
789
+ redis_shard_ports = redis_shard_ports.split(",")
790
+ # Infer the number of Redis shards from the ports if the number is
791
+ # not provided.
792
+ num_redis_shards = len(redis_shard_ports)
793
+
794
+ # This logic is deprecated and will be removed later.
795
+ if address is not None:
796
+ cli_logger.warning(
797
+ "Specifying {} for external Redis address is deprecated. "
798
+ "Please specify environment variable {}={} instead.",
799
+ cf.bold("--address"),
800
+ cf.bold("RAY_REDIS_ADDRESS"),
801
+ address,
802
+ )
803
+ external_addresses = address.split(",")
804
+
805
+ # We reuse primary redis as sharding when there's only one
806
+ # instance provided.
807
+ if len(external_addresses) == 1:
808
+ external_addresses.append(external_addresses[0])
809
+
810
+ ray_params.update_if_absent(external_addresses=external_addresses)
811
+ num_redis_shards = len(external_addresses) - 1
812
+ if redis_password == ray_constants.REDIS_DEFAULT_PASSWORD:
813
+ cli_logger.warning(
814
+ "`{}` should not be specified as empty string if "
815
+ "external redis server(s) `{}` points to requires "
816
+ "password.",
817
+ cf.bold("--redis-password"),
818
+ cf.bold("--address"),
819
+ )
820
+
821
+ # Get the node IP address if one is not provided.
822
+ ray_params.update_if_absent(node_ip_address=services.get_node_ip_address())
823
+ cli_logger.labeled_value("Local node IP", ray_params.node_ip_address)
824
+
825
+ # Initialize Redis settings.
826
+ ray_params.update_if_absent(
827
+ redis_shard_ports=redis_shard_ports,
828
+ redis_max_memory=redis_max_memory,
829
+ num_redis_shards=num_redis_shards,
830
+ redis_max_clients=None,
831
+ )
832
+
833
+ # Fail early when starting a new cluster when one is already running
834
+ if address is None:
835
+ default_address = f"{ray_params.node_ip_address}:{port}"
836
+ bootstrap_address = services.find_bootstrap_address(temp_dir)
837
+ if (
838
+ default_address == bootstrap_address
839
+ and bootstrap_address in services.find_gcs_addresses()
840
+ ):
841
+ # The default address is already in use by a local running GCS
842
+ # instance.
843
+ raise ConnectionError(
844
+ f"Ray is trying to start at {default_address}, "
845
+ f"but is already running at {bootstrap_address}. "
846
+ "Please specify a different port using the `--port`"
847
+ " flag of `ray start` command."
848
+ )
849
+
850
+ node = ray._private.node.Node(
851
+ ray_params, head=True, shutdown_at_exit=block, spawn_reaper=block
852
+ )
853
+
854
+ bootstrap_address = node.address
855
+
856
+ # this is a noop if new-style is not set, so the old logger calls
857
+ # are still in place
858
+ cli_logger.newline()
859
+ startup_msg = "Ray runtime started."
860
+ cli_logger.success("-" * len(startup_msg))
861
+ cli_logger.success(startup_msg)
862
+ cli_logger.success("-" * len(startup_msg))
863
+ cli_logger.newline()
864
+ with cli_logger.group("Next steps"):
865
+ dashboard_url = node.address_info["webui_url"]
866
+ if ray_constants.ENABLE_RAY_CLUSTER:
867
+ cli_logger.print("To add another node to this Ray cluster, run")
868
+ # NOTE(kfstorm): Java driver rely on this line to get the address
869
+ # of the cluster. Please be careful when updating this line.
870
+ cli_logger.print(
871
+ cf.bold(" {} ray start --address='{}'"),
872
+ f" {ray_constants.ENABLE_RAY_CLUSTERS_ENV_VAR}=1"
873
+ if ray_constants.IS_WINDOWS_OR_OSX
874
+ else "",
875
+ bootstrap_address,
876
+ )
877
+
878
+ cli_logger.newline()
879
+ cli_logger.print("To connect to this Ray cluster:")
880
+ with cli_logger.indented():
881
+ cli_logger.print("{} ray", cf.magenta("import"))
882
+ cli_logger.print(
883
+ "ray{}init({})",
884
+ cf.magenta("."),
885
+ "_node_ip_address{}{}".format(
886
+ cf.magenta("="), cf.yellow("'" + node_ip_address + "'")
887
+ )
888
+ if include_node_ip_address
889
+ else "",
890
+ )
891
+
892
+ if dashboard_url:
893
+ cli_logger.newline()
894
+ cli_logger.print("To submit a Ray job using the Ray Jobs CLI:")
895
+ cli_logger.print(
896
+ cf.bold(
897
+ " RAY_ADDRESS='http://{}' ray job submit "
898
+ "--working-dir . "
899
+ "-- python my_script.py"
900
+ ),
901
+ dashboard_url,
902
+ )
903
+ cli_logger.newline()
904
+ cli_logger.print(
905
+ "See https://docs.ray.io/en/latest/cluster/running-applications"
906
+ "/job-submission/index.html "
907
+ )
908
+ cli_logger.print(
909
+ "for more information on submitting Ray jobs to the Ray cluster."
910
+ )
911
+
912
+ cli_logger.newline()
913
+ cli_logger.print("To terminate the Ray runtime, run")
914
+ cli_logger.print(cf.bold(" ray stop"))
915
+
916
+ cli_logger.newline()
917
+ cli_logger.print("To view the status of the cluster, use")
918
+ cli_logger.print(" {}".format(cf.bold("ray status")))
919
+
920
+ if dashboard_url:
921
+ cli_logger.newline()
922
+ cli_logger.print("To monitor and debug Ray, view the dashboard at ")
923
+ cli_logger.print(
924
+ " {}".format(
925
+ cf.bold(dashboard_url),
926
+ )
927
+ )
928
+
929
+ cli_logger.newline()
930
+ cli_logger.print(
931
+ cf.underlined(
932
+ "If connection to the dashboard fails, check your "
933
+ "firewall settings and "
934
+ "network configuration."
935
+ )
936
+ )
937
+ ray_params.gcs_address = bootstrap_address
938
+ else:
939
+ # Start worker node.
940
+ if not ray_constants.ENABLE_RAY_CLUSTER:
941
+ cli_logger.abort(
942
+ "Multi-node Ray clusters are not supported on Windows and OSX. "
943
+ "Restart the Ray cluster with the environment variable `{}=1` "
944
+ "to proceed anyway.",
945
+ cf.bold(ray_constants.ENABLE_RAY_CLUSTERS_ENV_VAR),
946
+ )
947
+ raise Exception(
948
+ "Multi-node Ray clusters are not supported on Windows and OSX. "
949
+ "Restart the Ray cluster with the environment variable "
950
+ f"`{ray_constants.ENABLE_RAY_CLUSTERS_ENV_VAR}=1` to proceed "
951
+ "anyway.",
952
+ )
953
+
954
+ # Ensure `--address` flag is specified.
955
+ if address is None:
956
+ cli_logger.abort(
957
+ "`{}` is a required flag unless starting a head node with `{}`.",
958
+ cf.bold("--address"),
959
+ cf.bold("--head"),
960
+ )
961
+ raise Exception(
962
+ "`--address` is a required flag unless starting a "
963
+ "head node with `--head`."
964
+ )
965
+
966
+ # Raise error if any head-only flag are specified.
967
+ head_only_flags = {
968
+ "--port": port,
969
+ "--redis-shard-ports": redis_shard_ports,
970
+ "--include-dashboard": include_dashboard,
971
+ }
972
+ for flag, val in head_only_flags.items():
973
+ if val is None:
974
+ continue
975
+ cli_logger.abort(
976
+ "`{}` should only be specified when starting head node with `{}`.",
977
+ cf.bold(flag),
978
+ cf.bold("--head"),
979
+ )
980
+ raise ValueError(
981
+ f"{flag} should only be specified when starting head node "
982
+ "with `--head`."
983
+ )
984
+
985
+ # Start Ray on a non-head node.
986
+ bootstrap_address = services.canonicalize_bootstrap_address(
987
+ address, temp_dir=temp_dir
988
+ )
989
+
990
+ if bootstrap_address is None:
991
+ cli_logger.abort(
992
+ "Cannot canonicalize address `{}={}`.",
993
+ cf.bold("--address"),
994
+ cf.bold(address),
995
+ )
996
+ raise Exception("Cannot canonicalize address " f"`--address={address}`.")
997
+
998
+ ray_params.gcs_address = bootstrap_address
999
+
1000
+ # Get the node IP address if one is not provided.
1001
+ ray_params.update_if_absent(
1002
+ node_ip_address=services.get_node_ip_address(bootstrap_address)
1003
+ )
1004
+
1005
+ cli_logger.labeled_value("Local node IP", ray_params.node_ip_address)
1006
+
1007
+ node = ray._private.node.Node(
1008
+ ray_params, head=False, shutdown_at_exit=block, spawn_reaper=block
1009
+ )
1010
+ temp_dir = node.get_temp_dir_path()
1011
+
1012
+ # Ray and Python versions should probably be checked before
1013
+ # initializing Node.
1014
+ node.check_version_info()
1015
+
1016
+ cli_logger.newline()
1017
+ startup_msg = "Ray runtime started."
1018
+ cli_logger.success("-" * len(startup_msg))
1019
+ cli_logger.success(startup_msg)
1020
+ cli_logger.success("-" * len(startup_msg))
1021
+ cli_logger.newline()
1022
+ cli_logger.print("To terminate the Ray runtime, run")
1023
+ cli_logger.print(cf.bold(" ray stop"))
1024
+ cli_logger.flush()
1025
+
1026
+ assert ray_params.gcs_address is not None
1027
+ ray._private.utils.write_ray_address(ray_params.gcs_address, temp_dir)
1028
+
1029
+ if block:
1030
+ cli_logger.newline()
1031
+ with cli_logger.group(cf.bold("--block")):
1032
+ cli_logger.print(
1033
+ "This command will now block forever until terminated by a signal."
1034
+ )
1035
+ cli_logger.print(
1036
+ "Running subprocesses are monitored and a message will be "
1037
+ "printed if any of them terminate unexpectedly. Subprocesses "
1038
+ "exit with SIGTERM will be treated as graceful, thus NOT reported."
1039
+ )
1040
+ cli_logger.flush()
1041
+
1042
+ while True:
1043
+ time.sleep(1)
1044
+ deceased = node.dead_processes()
1045
+
1046
+ # Report unexpected exits of subprocesses with unexpected return codes.
1047
+ # We are explicitly expecting SIGTERM because this is how `ray stop` sends
1048
+ # shutdown signal to subprocesses, i.e. log_monitor, raylet...
1049
+ # NOTE(rickyyx): We are treating 128+15 as an expected return code since
1050
+ # this is what autoscaler/_private/monitor.py does upon SIGTERM
1051
+ # handling.
1052
+ expected_return_codes = [
1053
+ 0,
1054
+ signal.SIGTERM,
1055
+ -1 * signal.SIGTERM,
1056
+ 128 + signal.SIGTERM,
1057
+ ]
1058
+ unexpected_deceased = [
1059
+ (process_type, process)
1060
+ for process_type, process in deceased
1061
+ if process.returncode not in expected_return_codes
1062
+ ]
1063
+ if len(unexpected_deceased) > 0:
1064
+ cli_logger.newline()
1065
+ cli_logger.error("Some Ray subprocesses exited unexpectedly:")
1066
+
1067
+ with cli_logger.indented():
1068
+ for process_type, process in unexpected_deceased:
1069
+ cli_logger.error(
1070
+ "{}",
1071
+ cf.bold(str(process_type)),
1072
+ _tags={"exit code": str(process.returncode)},
1073
+ )
1074
+
1075
+ cli_logger.newline()
1076
+ cli_logger.error("Remaining processes will be killed.")
1077
+ # explicitly kill all processes since atexit handlers
1078
+ # will not exit with errors.
1079
+ node.kill_all_processes(check_alive=False, allow_graceful=False)
1080
+ os._exit(1)
1081
+ # not-reachable
1082
+
1083
+
1084
+ @cli.command()
1085
+ @click.option(
1086
+ "-f",
1087
+ "--force",
1088
+ is_flag=True,
1089
+ help="If set, ray will send SIGKILL instead of SIGTERM.",
1090
+ )
1091
+ @click.option(
1092
+ "-g",
1093
+ "--grace-period",
1094
+ default=16,
1095
+ help=(
1096
+ "The time in seconds ray waits for processes to be properly terminated. "
1097
+ "If processes are not terminated within the grace period, "
1098
+ "they are forcefully terminated after the grace period. "
1099
+ ),
1100
+ )
1101
+ @add_click_logging_options
1102
+ @PublicAPI
1103
+ def stop(force: bool, grace_period: int):
1104
+ """Stop Ray processes manually on the local machine."""
1105
+ is_linux = sys.platform.startswith("linux")
1106
+ total_procs_found = 0
1107
+ total_procs_stopped = 0
1108
+ procs_not_gracefully_killed = []
1109
+
1110
+ def kill_procs(
1111
+ force: bool, grace_period: int, processes_to_kill: List[str]
1112
+ ) -> Tuple[int, int, List[psutil.Process]]:
1113
+ """Find all processes from `processes_to_kill` and terminate them.
1114
+
1115
+ Unless `force` is specified, it gracefully kills processes. If
1116
+ processes are not cleaned within `grace_period`, it force kill all
1117
+ remaining processes.
1118
+
1119
+ Returns:
1120
+ total_procs_found: Total number of processes found from
1121
+ `processes_to_kill` is added.
1122
+ total_procs_stopped: Total number of processes gracefully
1123
+ stopped from `processes_to_kill` is added.
1124
+ procs_not_gracefully_killed: If processes are not killed
1125
+ gracefully, they are added here.
1126
+ """
1127
+ process_infos = []
1128
+ for proc in psutil.process_iter(["name", "cmdline"]):
1129
+ try:
1130
+ process_infos.append((proc, proc.name(), proc.cmdline()))
1131
+ except psutil.Error:
1132
+ pass
1133
+
1134
+ stopped = []
1135
+ for keyword, filter_by_cmd in processes_to_kill:
1136
+ if filter_by_cmd and is_linux and len(keyword) > 15:
1137
+ # getting here is an internal bug, so we do not use cli_logger
1138
+ msg = (
1139
+ "The filter string should not be more than {} "
1140
+ "characters. Actual length: {}. Filter: {}"
1141
+ ).format(15, len(keyword), keyword)
1142
+ raise ValueError(msg)
1143
+
1144
+ found = []
1145
+ for candidate in process_infos:
1146
+ proc, proc_cmd, proc_args = candidate
1147
+ corpus = (
1148
+ proc_cmd if filter_by_cmd else subprocess.list2cmdline(proc_args)
1149
+ )
1150
+ if keyword in corpus:
1151
+ found.append(candidate)
1152
+ for proc, proc_cmd, proc_args in found:
1153
+ proc_string = str(subprocess.list2cmdline(proc_args))
1154
+ try:
1155
+ if force:
1156
+ proc.kill()
1157
+ else:
1158
+ # TODO(mehrdadn): On Windows, this is forceful termination.
1159
+ # We don't want CTRL_BREAK_EVENT, because that would
1160
+ # terminate the entire process group. What to do?
1161
+ proc.terminate()
1162
+
1163
+ if force:
1164
+ cli_logger.verbose(
1165
+ "Killed `{}` {} ",
1166
+ cf.bold(proc_string),
1167
+ cf.dimmed("(via SIGKILL)"),
1168
+ )
1169
+ else:
1170
+ cli_logger.verbose(
1171
+ "Send termination request to `{}` {}",
1172
+ cf.bold(proc_string),
1173
+ cf.dimmed("(via SIGTERM)"),
1174
+ )
1175
+
1176
+ stopped.append(proc)
1177
+ except psutil.NoSuchProcess:
1178
+ cli_logger.verbose(
1179
+ "Attempted to stop `{}`, but process was already dead.",
1180
+ cf.bold(proc_string),
1181
+ )
1182
+ except (psutil.Error, OSError) as ex:
1183
+ cli_logger.error(
1184
+ "Could not terminate `{}` due to {}",
1185
+ cf.bold(proc_string),
1186
+ str(ex),
1187
+ )
1188
+
1189
+ # Wait for the processes to actually stop.
1190
+ # Dedup processes.
1191
+ stopped, alive = psutil.wait_procs(stopped, timeout=0)
1192
+ procs_to_kill = stopped + alive
1193
+ total_found = len(procs_to_kill)
1194
+
1195
+ # Wait for grace period to terminate processes.
1196
+ gone_procs = set()
1197
+
1198
+ def on_terminate(proc):
1199
+ gone_procs.add(proc)
1200
+ cli_logger.print(f"{len(gone_procs)}/{total_found} stopped.", end="\r")
1201
+
1202
+ stopped, alive = psutil.wait_procs(
1203
+ procs_to_kill, timeout=grace_period, callback=on_terminate
1204
+ )
1205
+ total_stopped = len(stopped)
1206
+
1207
+ # For processes that are not killed within the grace period,
1208
+ # we send force termination signals.
1209
+ for proc in alive:
1210
+ proc.kill()
1211
+ # Wait a little bit to make sure processes are killed forcefully.
1212
+ psutil.wait_procs(alive, timeout=2)
1213
+ return total_found, total_stopped, alive
1214
+
1215
+ # Process killing procedure: we put processes into 3 buckets.
1216
+ # Bucket 1: raylet
1217
+ # Bucket 2: all other processes, e.g. dashboard, runtime env agents
1218
+ # Bucket 3: gcs_server.
1219
+ #
1220
+ # For each bucket, we send sigterm to all processes, then wait for 30s, then if
1221
+ # they are still alive, send sigkill.
1222
+ processes_to_kill = RAY_PROCESSES
1223
+ # Raylet should exit before all other processes exit.
1224
+ # Otherwise, fate-sharing agents will complain and exit.
1225
+ assert processes_to_kill[0][0] == "raylet"
1226
+
1227
+ # GCS should exit after all other processes exit.
1228
+ # Otherwise, some of processes may exit with an unexpected
1229
+ # exit code which breaks ray start --block.
1230
+ assert processes_to_kill[-1][0] == "gcs_server"
1231
+
1232
+ buckets = [[processes_to_kill[0]], processes_to_kill[1:-1], [processes_to_kill[-1]]]
1233
+
1234
+ for bucket in buckets:
1235
+ found, stopped, alive = kill_procs(force, grace_period / len(buckets), bucket)
1236
+ total_procs_found += found
1237
+ total_procs_stopped += stopped
1238
+ procs_not_gracefully_killed.extend(alive)
1239
+
1240
+ # Print the termination result.
1241
+ if total_procs_found == 0:
1242
+ cli_logger.print("Did not find any active Ray processes.")
1243
+ else:
1244
+ if total_procs_stopped == total_procs_found:
1245
+ cli_logger.success("Stopped all {} Ray processes.", total_procs_stopped)
1246
+ else:
1247
+ cli_logger.warning(
1248
+ f"Stopped only {total_procs_stopped} out of {total_procs_found} "
1249
+ f"Ray processes within the grace period {grace_period} seconds. "
1250
+ f"Set `{cf.bold('-v')}` to see more details. "
1251
+ f"Remaining processes {procs_not_gracefully_killed} "
1252
+ "will be forcefully terminated.",
1253
+ )
1254
+ cli_logger.warning(
1255
+ f"You can also use `{cf.bold('--force')}` to forcefully terminate "
1256
+ "processes or set higher `--grace-period` to wait longer time for "
1257
+ "proper termination."
1258
+ )
1259
+
1260
+ # NOTE(swang): This will not reset the cluster address for a user-defined
1261
+ # temp_dir. This is fine since it will get overwritten the next time we
1262
+ # call `ray start`.
1263
+ ray._private.utils.reset_ray_address()
1264
+
1265
+
1266
+ @cli.command()
1267
+ @click.argument("cluster_config_file", required=True, type=str)
1268
+ @click.option(
1269
+ "--min-workers",
1270
+ required=False,
1271
+ type=int,
1272
+ help="Override the configured min worker node count for the cluster.",
1273
+ )
1274
+ @click.option(
1275
+ "--max-workers",
1276
+ required=False,
1277
+ type=int,
1278
+ help="Override the configured max worker node count for the cluster.",
1279
+ )
1280
+ @click.option(
1281
+ "--no-restart",
1282
+ is_flag=True,
1283
+ default=False,
1284
+ help=(
1285
+ "Whether to skip restarting Ray services during the update. "
1286
+ "This avoids interrupting running jobs."
1287
+ ),
1288
+ )
1289
+ @click.option(
1290
+ "--restart-only",
1291
+ is_flag=True,
1292
+ default=False,
1293
+ help=(
1294
+ "Whether to skip running setup commands and only restart Ray. "
1295
+ "This cannot be used with 'no-restart'."
1296
+ ),
1297
+ )
1298
+ @click.option(
1299
+ "--yes", "-y", is_flag=True, default=False, help="Don't ask for confirmation."
1300
+ )
1301
+ @click.option(
1302
+ "--cluster-name",
1303
+ "-n",
1304
+ required=False,
1305
+ type=str,
1306
+ help="Override the configured cluster name.",
1307
+ )
1308
+ @click.option(
1309
+ "--no-config-cache",
1310
+ is_flag=True,
1311
+ default=False,
1312
+ help="Disable the local cluster config cache.",
1313
+ )
1314
+ @click.option(
1315
+ "--redirect-command-output",
1316
+ is_flag=True,
1317
+ default=False,
1318
+ help="Whether to redirect command output to a file.",
1319
+ )
1320
+ @click.option(
1321
+ "--use-login-shells/--use-normal-shells",
1322
+ is_flag=True,
1323
+ default=True,
1324
+ help=(
1325
+ "Ray uses login shells (bash --login -i) to run cluster commands "
1326
+ "by default. If your workflow is compatible with normal shells, "
1327
+ "this can be disabled for a better user experience."
1328
+ ),
1329
+ )
1330
+ @click.option(
1331
+ "--disable-usage-stats",
1332
+ is_flag=True,
1333
+ default=False,
1334
+ help="If True, the usage stats collection will be disabled.",
1335
+ )
1336
+ @add_click_logging_options
1337
+ @PublicAPI
1338
+ def up(
1339
+ cluster_config_file,
1340
+ min_workers,
1341
+ max_workers,
1342
+ no_restart,
1343
+ restart_only,
1344
+ yes,
1345
+ cluster_name,
1346
+ no_config_cache,
1347
+ redirect_command_output,
1348
+ use_login_shells,
1349
+ disable_usage_stats,
1350
+ ):
1351
+ """Create or update a Ray cluster."""
1352
+ if disable_usage_stats:
1353
+ usage_lib.set_usage_stats_enabled_via_env_var(False)
1354
+
1355
+ if restart_only or no_restart:
1356
+ cli_logger.doassert(
1357
+ restart_only != no_restart,
1358
+ "`{}` is incompatible with `{}`.",
1359
+ cf.bold("--restart-only"),
1360
+ cf.bold("--no-restart"),
1361
+ )
1362
+ assert (
1363
+ restart_only != no_restart
1364
+ ), "Cannot set both 'restart_only' and 'no_restart' at the same time!"
1365
+
1366
+ if urllib.parse.urlparse(cluster_config_file).scheme in ("http", "https"):
1367
+ try:
1368
+ response = urllib.request.urlopen(cluster_config_file, timeout=5)
1369
+ content = response.read()
1370
+ file_name = cluster_config_file.split("/")[-1]
1371
+ with open(file_name, "wb") as f:
1372
+ f.write(content)
1373
+ cluster_config_file = file_name
1374
+ except urllib.error.HTTPError as e:
1375
+ cli_logger.warning("{}", str(e))
1376
+ cli_logger.warning("Could not download remote cluster configuration file.")
1377
+ create_or_update_cluster(
1378
+ config_file=cluster_config_file,
1379
+ override_min_workers=min_workers,
1380
+ override_max_workers=max_workers,
1381
+ no_restart=no_restart,
1382
+ restart_only=restart_only,
1383
+ yes=yes,
1384
+ override_cluster_name=cluster_name,
1385
+ no_config_cache=no_config_cache,
1386
+ redirect_command_output=redirect_command_output,
1387
+ use_login_shells=use_login_shells,
1388
+ )
1389
+
1390
+
1391
+ @cli.command()
1392
+ @click.argument("cluster_config_file", required=True, type=str)
1393
+ @click.option(
1394
+ "--yes", "-y", is_flag=True, default=False, help="Don't ask for confirmation."
1395
+ )
1396
+ @click.option(
1397
+ "--workers-only", is_flag=True, default=False, help="Only destroy the workers."
1398
+ )
1399
+ @click.option(
1400
+ "--cluster-name",
1401
+ "-n",
1402
+ required=False,
1403
+ type=str,
1404
+ help="Override the configured cluster name.",
1405
+ )
1406
+ @click.option(
1407
+ "--keep-min-workers",
1408
+ is_flag=True,
1409
+ default=False,
1410
+ help="Retain the minimal amount of workers specified in the config.",
1411
+ )
1412
+ @add_click_logging_options
1413
+ @PublicAPI
1414
+ def down(cluster_config_file, yes, workers_only, cluster_name, keep_min_workers):
1415
+ """Tear down a Ray cluster."""
1416
+ teardown_cluster(
1417
+ cluster_config_file, yes, workers_only, cluster_name, keep_min_workers
1418
+ )
1419
+
1420
+
1421
+ @cli.command(hidden=True)
1422
+ @click.argument("cluster_config_file", required=True, type=str)
1423
+ @click.option(
1424
+ "--yes", "-y", is_flag=True, default=False, help="Don't ask for confirmation."
1425
+ )
1426
+ @click.option(
1427
+ "--hard",
1428
+ is_flag=True,
1429
+ default=False,
1430
+ help="Terminates the node via node provider (defaults to a 'soft kill'"
1431
+ " which terminates Ray but does not actually delete the instances).",
1432
+ )
1433
+ @click.option(
1434
+ "--cluster-name",
1435
+ "-n",
1436
+ required=False,
1437
+ type=str,
1438
+ help="Override the configured cluster name.",
1439
+ )
1440
+ def kill_random_node(cluster_config_file, yes, hard, cluster_name):
1441
+ """Kills a random Ray node. For testing purposes only."""
1442
+ click.echo(
1443
+ "Killed node with IP " + kill_node(cluster_config_file, yes, hard, cluster_name)
1444
+ )
1445
+
1446
+
1447
+ @cli.command()
1448
+ @click.argument("cluster_config_file", required=True, type=str)
1449
+ @click.option(
1450
+ "--lines", required=False, default=100, type=int, help="Number of lines to tail."
1451
+ )
1452
+ @click.option(
1453
+ "--cluster-name",
1454
+ "-n",
1455
+ required=False,
1456
+ type=str,
1457
+ help="Override the configured cluster name.",
1458
+ )
1459
+ @add_click_logging_options
1460
+ def monitor(cluster_config_file, lines, cluster_name):
1461
+ """Tails the autoscaler logs of a Ray cluster."""
1462
+ monitor_cluster(cluster_config_file, lines, cluster_name)
1463
+
1464
+
1465
+ @cli.command()
1466
+ @click.argument("cluster_config_file", required=True, type=str)
1467
+ @click.option(
1468
+ "--start", is_flag=True, default=False, help="Start the cluster if needed."
1469
+ )
1470
+ @click.option(
1471
+ "--screen", is_flag=True, default=False, help="Run the command in screen."
1472
+ )
1473
+ @click.option("--tmux", is_flag=True, default=False, help="Run the command in tmux.")
1474
+ @click.option(
1475
+ "--cluster-name",
1476
+ "-n",
1477
+ required=False,
1478
+ type=str,
1479
+ help="Override the configured cluster name.",
1480
+ )
1481
+ @click.option(
1482
+ "--no-config-cache",
1483
+ is_flag=True,
1484
+ default=False,
1485
+ help="Disable the local cluster config cache.",
1486
+ )
1487
+ @click.option("--new", "-N", is_flag=True, help="Force creation of a new screen.")
1488
+ @click.option(
1489
+ "--port-forward",
1490
+ "-p",
1491
+ required=False,
1492
+ multiple=True,
1493
+ type=int,
1494
+ help="Port to forward. Use this multiple times to forward multiple ports.",
1495
+ )
1496
+ @add_click_logging_options
1497
+ @PublicAPI
1498
+ def attach(
1499
+ cluster_config_file,
1500
+ start,
1501
+ screen,
1502
+ tmux,
1503
+ cluster_name,
1504
+ no_config_cache,
1505
+ new,
1506
+ port_forward,
1507
+ ):
1508
+ """Create or attach to a SSH session to a Ray cluster."""
1509
+ port_forward = [(port, port) for port in list(port_forward)]
1510
+ attach_cluster(
1511
+ cluster_config_file,
1512
+ start,
1513
+ screen,
1514
+ tmux,
1515
+ cluster_name,
1516
+ no_config_cache=no_config_cache,
1517
+ new=new,
1518
+ port_forward=port_forward,
1519
+ )
1520
+
1521
+
1522
+ @cli.command()
1523
+ @click.argument("cluster_config_file", required=True, type=str)
1524
+ @click.argument("source", required=False, type=str)
1525
+ @click.argument("target", required=False, type=str)
1526
+ @click.option(
1527
+ "--cluster-name",
1528
+ "-n",
1529
+ required=False,
1530
+ type=str,
1531
+ help="Override the configured cluster name.",
1532
+ )
1533
+ @add_click_logging_options
1534
+ def rsync_down(cluster_config_file, source, target, cluster_name):
1535
+ """Download specific files from a Ray cluster."""
1536
+ rsync(cluster_config_file, source, target, cluster_name, down=True)
1537
+
1538
+
1539
+ @cli.command()
1540
+ @click.argument("cluster_config_file", required=True, type=str)
1541
+ @click.argument("source", required=False, type=str)
1542
+ @click.argument("target", required=False, type=str)
1543
+ @click.option(
1544
+ "--cluster-name",
1545
+ "-n",
1546
+ required=False,
1547
+ type=str,
1548
+ help="Override the configured cluster name.",
1549
+ )
1550
+ @click.option(
1551
+ "--all-nodes",
1552
+ "-A",
1553
+ is_flag=True,
1554
+ required=False,
1555
+ help="Upload to all nodes (workers and head).",
1556
+ )
1557
+ @add_click_logging_options
1558
+ def rsync_up(cluster_config_file, source, target, cluster_name, all_nodes):
1559
+ """Upload specific files to a Ray cluster."""
1560
+ if all_nodes:
1561
+ cli_logger.warning(
1562
+ "WARNING: the `all_nodes` option is deprecated and will be "
1563
+ "removed in the future. "
1564
+ "Rsync to worker nodes is not reliable since workers may be "
1565
+ "added during autoscaling. Please use the `file_mounts` "
1566
+ "feature instead for consistent file sync in autoscaling clusters"
1567
+ )
1568
+
1569
+ rsync(
1570
+ cluster_config_file,
1571
+ source,
1572
+ target,
1573
+ cluster_name,
1574
+ down=False,
1575
+ all_nodes=all_nodes,
1576
+ )
1577
+
1578
+
1579
+ @cli.command(context_settings={"ignore_unknown_options": True})
1580
+ @click.argument("cluster_config_file", required=True, type=str)
1581
+ @click.option(
1582
+ "--stop",
1583
+ is_flag=True,
1584
+ default=False,
1585
+ help="Stop the cluster after the command finishes running.",
1586
+ )
1587
+ @click.option(
1588
+ "--start", is_flag=True, default=False, help="Start the cluster if needed."
1589
+ )
1590
+ @click.option(
1591
+ "--screen", is_flag=True, default=False, help="Run the command in a screen."
1592
+ )
1593
+ @click.option("--tmux", is_flag=True, default=False, help="Run the command in tmux.")
1594
+ @click.option(
1595
+ "--cluster-name",
1596
+ "-n",
1597
+ required=False,
1598
+ type=str,
1599
+ help="Override the configured cluster name.",
1600
+ )
1601
+ @click.option(
1602
+ "--no-config-cache",
1603
+ is_flag=True,
1604
+ default=False,
1605
+ help="Disable the local cluster config cache.",
1606
+ )
1607
+ @click.option(
1608
+ "--port-forward",
1609
+ "-p",
1610
+ required=False,
1611
+ multiple=True,
1612
+ type=int,
1613
+ help="Port to forward. Use this multiple times to forward multiple ports.",
1614
+ )
1615
+ @click.argument("script", required=True, type=str)
1616
+ @click.option(
1617
+ "--args",
1618
+ required=False,
1619
+ type=str,
1620
+ help="(deprecated) Use '-- --arg1 --arg2' for script args.",
1621
+ )
1622
+ @click.argument("script_args", nargs=-1)
1623
+ @click.option(
1624
+ "--disable-usage-stats",
1625
+ is_flag=True,
1626
+ default=False,
1627
+ help="If True, the usage stats collection will be disabled.",
1628
+ )
1629
+ @click.option(
1630
+ "--extra-screen-args",
1631
+ default=None,
1632
+ help="if screen is enabled, add the provided args to it. A useful example "
1633
+ "usage scenario is passing --extra-screen-args='-Logfile /full/path/blah_log.txt'"
1634
+ " as it redirects screen output also to a custom file",
1635
+ )
1636
+ @add_click_logging_options
1637
+ def submit(
1638
+ cluster_config_file,
1639
+ screen,
1640
+ tmux,
1641
+ stop,
1642
+ start,
1643
+ cluster_name,
1644
+ no_config_cache,
1645
+ port_forward,
1646
+ script,
1647
+ args,
1648
+ script_args,
1649
+ disable_usage_stats,
1650
+ extra_screen_args: Optional[str] = None,
1651
+ ):
1652
+ """Uploads and runs a script on the specified cluster.
1653
+
1654
+ The script is automatically synced to the following location:
1655
+
1656
+ os.path.join("~", os.path.basename(script))
1657
+
1658
+ Example:
1659
+ ray submit [CLUSTER.YAML] experiment.py -- --smoke-test
1660
+ """
1661
+ cli_logger.doassert(
1662
+ not (screen and tmux),
1663
+ "`{}` and `{}` are incompatible.",
1664
+ cf.bold("--screen"),
1665
+ cf.bold("--tmux"),
1666
+ )
1667
+ cli_logger.doassert(
1668
+ not (script_args and args),
1669
+ "`{0}` and `{1}` are incompatible. Use only `{1}`.\nExample: `{2}`",
1670
+ cf.bold("--args"),
1671
+ cf.bold("-- <args ...>"),
1672
+ cf.bold("ray submit script.py -- --arg=123 --flag"),
1673
+ )
1674
+
1675
+ assert not (screen and tmux), "Can specify only one of `screen` or `tmux`."
1676
+ assert not (script_args and args), "Use -- --arg1 --arg2 for script args."
1677
+
1678
+ if (extra_screen_args is not None) and (not screen):
1679
+ cli_logger.abort(
1680
+ "To use extra_screen_args, it is required to use the --screen flag"
1681
+ )
1682
+
1683
+ if args:
1684
+ cli_logger.warning(
1685
+ "`{}` is deprecated and will be removed in the future.", cf.bold("--args")
1686
+ )
1687
+ cli_logger.warning(
1688
+ "Use `{}` instead. Example: `{}`.",
1689
+ cf.bold("-- <args ...>"),
1690
+ cf.bold("ray submit script.py -- --arg=123 --flag"),
1691
+ )
1692
+ cli_logger.newline()
1693
+
1694
+ if start:
1695
+ if disable_usage_stats:
1696
+ usage_lib.set_usage_stats_enabled_via_env_var(False)
1697
+
1698
+ create_or_update_cluster(
1699
+ config_file=cluster_config_file,
1700
+ override_min_workers=None,
1701
+ override_max_workers=None,
1702
+ no_restart=False,
1703
+ restart_only=False,
1704
+ yes=True,
1705
+ override_cluster_name=cluster_name,
1706
+ no_config_cache=no_config_cache,
1707
+ redirect_command_output=False,
1708
+ use_login_shells=True,
1709
+ )
1710
+ target = os.path.basename(script)
1711
+ target = os.path.join("~", target)
1712
+ rsync(
1713
+ cluster_config_file,
1714
+ script,
1715
+ target,
1716
+ cluster_name,
1717
+ no_config_cache=no_config_cache,
1718
+ down=False,
1719
+ )
1720
+
1721
+ command_parts = ["python", target]
1722
+ if script_args:
1723
+ command_parts += list(script_args)
1724
+ elif args is not None:
1725
+ command_parts += [args]
1726
+
1727
+ port_forward = [(port, port) for port in list(port_forward)]
1728
+ cmd = " ".join(command_parts)
1729
+ exec_cluster(
1730
+ cluster_config_file,
1731
+ cmd=cmd,
1732
+ run_env="docker",
1733
+ screen=screen,
1734
+ tmux=tmux,
1735
+ stop=stop,
1736
+ start=False,
1737
+ override_cluster_name=cluster_name,
1738
+ no_config_cache=no_config_cache,
1739
+ port_forward=port_forward,
1740
+ extra_screen_args=extra_screen_args,
1741
+ )
1742
+
1743
+
1744
+ @cli.command()
1745
+ @click.argument("cluster_config_file", required=True, type=str)
1746
+ @click.argument("cmd", required=True, type=str)
1747
+ @click.option(
1748
+ "--run-env",
1749
+ required=False,
1750
+ type=click.Choice(RUN_ENV_TYPES),
1751
+ default="auto",
1752
+ help="Choose whether to execute this command in a container or directly on"
1753
+ " the cluster head. Only applies when docker is configured in the YAML.",
1754
+ )
1755
+ @click.option(
1756
+ "--stop",
1757
+ is_flag=True,
1758
+ default=False,
1759
+ help="Stop the cluster after the command finishes running.",
1760
+ )
1761
+ @click.option(
1762
+ "--start", is_flag=True, default=False, help="Start the cluster if needed."
1763
+ )
1764
+ @click.option(
1765
+ "--screen", is_flag=True, default=False, help="Run the command in a screen."
1766
+ )
1767
+ @click.option("--tmux", is_flag=True, default=False, help="Run the command in tmux.")
1768
+ @click.option(
1769
+ "--cluster-name",
1770
+ "-n",
1771
+ required=False,
1772
+ type=str,
1773
+ help="Override the configured cluster name.",
1774
+ )
1775
+ @click.option(
1776
+ "--no-config-cache",
1777
+ is_flag=True,
1778
+ default=False,
1779
+ help="Disable the local cluster config cache.",
1780
+ )
1781
+ @click.option(
1782
+ "--port-forward",
1783
+ "-p",
1784
+ required=False,
1785
+ multiple=True,
1786
+ type=int,
1787
+ help="Port to forward. Use this multiple times to forward multiple ports.",
1788
+ )
1789
+ @click.option(
1790
+ "--disable-usage-stats",
1791
+ is_flag=True,
1792
+ default=False,
1793
+ help="If True, the usage stats collection will be disabled.",
1794
+ )
1795
+ @add_click_logging_options
1796
+ def exec(
1797
+ cluster_config_file,
1798
+ cmd,
1799
+ run_env,
1800
+ screen,
1801
+ tmux,
1802
+ stop,
1803
+ start,
1804
+ cluster_name,
1805
+ no_config_cache,
1806
+ port_forward,
1807
+ disable_usage_stats,
1808
+ ):
1809
+ """Execute a command via SSH on a Ray cluster."""
1810
+ port_forward = [(port, port) for port in list(port_forward)]
1811
+
1812
+ if start:
1813
+ if disable_usage_stats:
1814
+ usage_lib.set_usage_stats_enabled_via_env_var(False)
1815
+
1816
+ exec_cluster(
1817
+ cluster_config_file,
1818
+ cmd=cmd,
1819
+ run_env=run_env,
1820
+ screen=screen,
1821
+ tmux=tmux,
1822
+ stop=stop,
1823
+ start=start,
1824
+ override_cluster_name=cluster_name,
1825
+ no_config_cache=no_config_cache,
1826
+ port_forward=port_forward,
1827
+ _allow_uninitialized_state=True,
1828
+ )
1829
+
1830
+
1831
+ @cli.command()
1832
+ @click.argument("cluster_config_file", required=True, type=str)
1833
+ @click.option(
1834
+ "--cluster-name",
1835
+ "-n",
1836
+ required=False,
1837
+ type=str,
1838
+ help="Override the configured cluster name.",
1839
+ )
1840
+ def get_head_ip(cluster_config_file, cluster_name):
1841
+ """Return the head node IP of a Ray cluster."""
1842
+ click.echo(get_head_node_ip(cluster_config_file, cluster_name))
1843
+
1844
+
1845
+ @cli.command()
1846
+ @click.argument("cluster_config_file", required=True, type=str)
1847
+ @click.option(
1848
+ "--cluster-name",
1849
+ "-n",
1850
+ required=False,
1851
+ type=str,
1852
+ help="Override the configured cluster name.",
1853
+ )
1854
+ def get_worker_ips(cluster_config_file, cluster_name):
1855
+ """Return the list of worker IPs of a Ray cluster."""
1856
+ worker_ips = get_worker_node_ips(cluster_config_file, cluster_name)
1857
+ click.echo("\n".join(worker_ips))
1858
+
1859
+
1860
+ @cli.command()
1861
+ def disable_usage_stats():
1862
+ """Disable usage stats collection.
1863
+
1864
+ This will not affect the current running clusters
1865
+ but clusters launched in the future.
1866
+ """
1867
+ usage_lib.set_usage_stats_enabled_via_config(enabled=False)
1868
+ print(
1869
+ "Usage stats disabled for future clusters. "
1870
+ "Restart any current running clusters for this to take effect."
1871
+ )
1872
+
1873
+
1874
+ @cli.command()
1875
+ def enable_usage_stats():
1876
+ """Enable usage stats collection.
1877
+
1878
+ This will not affect the current running clusters
1879
+ but clusters launched in the future.
1880
+ """
1881
+ usage_lib.set_usage_stats_enabled_via_config(enabled=True)
1882
+ print(
1883
+ "Usage stats enabled for future clusters. "
1884
+ "Restart any current running clusters for this to take effect."
1885
+ )
1886
+
1887
+
1888
+ @cli.command()
1889
+ def stack():
1890
+ """Take a stack dump of all Python workers on the local machine."""
1891
+ COMMAND = """
1892
+ pyspy=`which py-spy`
1893
+ if [ ! -e "$pyspy" ]; then
1894
+ echo "ERROR: Please 'pip install py-spy'" \
1895
+ "or 'pip install ray[default]' first."
1896
+ exit 1
1897
+ fi
1898
+ # Set IFS to iterate over lines instead of over words.
1899
+ export IFS="
1900
+ "
1901
+ # Call sudo to prompt for password before anything has been printed.
1902
+ sudo true
1903
+ workers=$(
1904
+ ps aux | grep -E ' ray::|default_worker.py' | grep -v raylet | grep -v grep
1905
+ )
1906
+ for worker in $workers; do
1907
+ echo "Stack dump for $worker";
1908
+ pid=`echo $worker | awk '{print $2}'`;
1909
+ case "$(uname -s)" in
1910
+ Linux*) native=--native;;
1911
+ *) native=;;
1912
+ esac
1913
+ sudo $pyspy dump --pid $pid $native;
1914
+ echo;
1915
+ done
1916
+ """
1917
+ subprocess.call(COMMAND, shell=True)
1918
+
1919
+
1920
+ @cli.command()
1921
+ def microbenchmark():
1922
+ """Run a local Ray microbenchmark on the current machine."""
1923
+ from ray._private.ray_perf import main
1924
+
1925
+ main()
1926
+
1927
+
1928
+ @cli.command()
1929
+ @click.option(
1930
+ "--address",
1931
+ required=False,
1932
+ type=str,
1933
+ help="Override the Ray address to connect to.",
1934
+ )
1935
+ def timeline(address):
1936
+ """Take a Chrome tracing timeline for a Ray cluster."""
1937
+ address = services.canonicalize_bootstrap_address_or_die(address)
1938
+ logger.info(f"Connecting to Ray instance at {address}.")
1939
+ ray.init(address=address)
1940
+ time = datetime.today().strftime("%Y-%m-%d_%H-%M-%S")
1941
+ filename = os.path.join(
1942
+ ray._private.utils.get_user_temp_dir(), f"ray-timeline-{time}.json"
1943
+ )
1944
+ ray.timeline(filename=filename)
1945
+ size = os.path.getsize(filename)
1946
+ logger.info(f"Trace file written to {filename} ({size} bytes).")
1947
+ logger.info("You can open this with chrome://tracing in the Chrome browser.")
1948
+
1949
+
1950
+ @cli.command()
1951
+ @click.option(
1952
+ "--address", required=False, type=str, help="Override the address to connect to."
1953
+ )
1954
+ @click.option(
1955
+ "--redis_password",
1956
+ required=False,
1957
+ type=str,
1958
+ default=ray_constants.REDIS_DEFAULT_PASSWORD,
1959
+ help="Connect to ray with redis_password.",
1960
+ )
1961
+ @click.option(
1962
+ "--group-by",
1963
+ type=click.Choice(["NODE_ADDRESS", "STACK_TRACE"]),
1964
+ default="NODE_ADDRESS",
1965
+ help="Group object references by a GroupByType \
1966
+ (e.g. NODE_ADDRESS or STACK_TRACE).",
1967
+ )
1968
+ @click.option(
1969
+ "--sort-by",
1970
+ type=click.Choice(["PID", "OBJECT_SIZE", "REFERENCE_TYPE"]),
1971
+ default="OBJECT_SIZE",
1972
+ help="Sort object references in ascending order by a SortingType \
1973
+ (e.g. PID, OBJECT_SIZE, or REFERENCE_TYPE).",
1974
+ )
1975
+ @click.option(
1976
+ "--units",
1977
+ type=click.Choice(["B", "KB", "MB", "GB"]),
1978
+ default="B",
1979
+ help="Specify unit metrics for displaying object sizes \
1980
+ (e.g. B, KB, MB, GB).",
1981
+ )
1982
+ @click.option(
1983
+ "--no-format",
1984
+ is_flag=True,
1985
+ type=bool,
1986
+ default=True,
1987
+ help="Display unformatted results. Defaults to true when \
1988
+ terminal width is less than 137 characters.",
1989
+ )
1990
+ @click.option(
1991
+ "--stats-only", is_flag=True, default=False, help="Display plasma store stats only."
1992
+ )
1993
+ @click.option(
1994
+ "--num-entries",
1995
+ "--n",
1996
+ type=int,
1997
+ default=None,
1998
+ help="Specify number of sorted entries per group.",
1999
+ )
2000
+ def memory(
2001
+ address,
2002
+ redis_password,
2003
+ group_by,
2004
+ sort_by,
2005
+ units,
2006
+ no_format,
2007
+ stats_only,
2008
+ num_entries,
2009
+ ):
2010
+ """Print object references held in a Ray cluster."""
2011
+ address = services.canonicalize_bootstrap_address_or_die(address)
2012
+ gcs_client = ray._raylet.GcsClient(address=address)
2013
+ _check_ray_version(gcs_client)
2014
+ time = datetime.now()
2015
+ header = "=" * 8 + f" Object references status: {time} " + "=" * 8
2016
+ mem_stats = memory_summary(
2017
+ address,
2018
+ group_by,
2019
+ sort_by,
2020
+ units,
2021
+ no_format,
2022
+ stats_only,
2023
+ num_entries,
2024
+ )
2025
+ print(f"{header}\n{mem_stats}")
2026
+
2027
+
2028
+ @cli.command()
2029
+ @click.option(
2030
+ "--address", required=False, type=str, help="Override the address to connect to."
2031
+ )
2032
+ @click.option(
2033
+ "--redis_password",
2034
+ required=False,
2035
+ type=str,
2036
+ default=ray_constants.REDIS_DEFAULT_PASSWORD,
2037
+ help="Connect to ray with redis_password.",
2038
+ )
2039
+ @click.option(
2040
+ "-v",
2041
+ "--verbose",
2042
+ required=False,
2043
+ is_flag=True,
2044
+ hidden=True,
2045
+ help="Experimental: Display additional debuggging information.",
2046
+ )
2047
+ @PublicAPI
2048
+ def status(address: str, redis_password: str, verbose: bool):
2049
+ """Print cluster status, including autoscaling info."""
2050
+ address = services.canonicalize_bootstrap_address_or_die(address)
2051
+ gcs_client = ray._raylet.GcsClient(address=address)
2052
+ _check_ray_version(gcs_client)
2053
+ ray.experimental.internal_kv._initialize_internal_kv(gcs_client)
2054
+ status = gcs_client.internal_kv_get(ray_constants.DEBUG_AUTOSCALING_STATUS.encode())
2055
+ error = gcs_client.internal_kv_get(ray_constants.DEBUG_AUTOSCALING_ERROR.encode())
2056
+ print(debug_status(status, error, verbose=verbose, address=address))
2057
+
2058
+
2059
+ @cli.command(hidden=True)
2060
+ @click.option(
2061
+ "--stream",
2062
+ "-S",
2063
+ required=False,
2064
+ type=bool,
2065
+ is_flag=True,
2066
+ default=False,
2067
+ help="If True, will stream the binary archive contents to stdout",
2068
+ )
2069
+ @click.option(
2070
+ "--output", "-o", required=False, type=str, default=None, help="Output file."
2071
+ )
2072
+ @click.option(
2073
+ "--logs/--no-logs",
2074
+ is_flag=True,
2075
+ default=True,
2076
+ help="Collect logs from ray session dir",
2077
+ )
2078
+ @click.option(
2079
+ "--debug-state/--no-debug-state",
2080
+ is_flag=True,
2081
+ default=True,
2082
+ help="Collect debug_state.txt from ray session dir",
2083
+ )
2084
+ @click.option(
2085
+ "--pip/--no-pip", is_flag=True, default=True, help="Collect installed pip packages"
2086
+ )
2087
+ @click.option(
2088
+ "--processes/--no-processes",
2089
+ is_flag=True,
2090
+ default=True,
2091
+ help="Collect info on running processes",
2092
+ )
2093
+ @click.option(
2094
+ "--processes-verbose/--no-processes-verbose",
2095
+ is_flag=True,
2096
+ default=True,
2097
+ help="Increase process information verbosity",
2098
+ )
2099
+ @click.option(
2100
+ "--tempfile",
2101
+ "-T",
2102
+ required=False,
2103
+ type=str,
2104
+ default=None,
2105
+ help="Temporary file to use",
2106
+ )
2107
+ def local_dump(
2108
+ stream: bool = False,
2109
+ output: Optional[str] = None,
2110
+ logs: bool = True,
2111
+ debug_state: bool = True,
2112
+ pip: bool = True,
2113
+ processes: bool = True,
2114
+ processes_verbose: bool = False,
2115
+ tempfile: Optional[str] = None,
2116
+ ):
2117
+ """Collect local data and package into an archive.
2118
+
2119
+ Usage:
2120
+
2121
+ ray local-dump [--stream/--output file]
2122
+
2123
+ This script is called on remote nodes to fetch their data.
2124
+ """
2125
+ # This may stream data to stdout, so no printing here
2126
+ get_local_dump_archive(
2127
+ stream=stream,
2128
+ output=output,
2129
+ logs=logs,
2130
+ debug_state=debug_state,
2131
+ pip=pip,
2132
+ processes=processes,
2133
+ processes_verbose=processes_verbose,
2134
+ tempfile=tempfile,
2135
+ )
2136
+
2137
+
2138
+ @cli.command()
2139
+ @click.argument("cluster_config_file", required=False, type=str)
2140
+ @click.option(
2141
+ "--host",
2142
+ "-h",
2143
+ required=False,
2144
+ type=str,
2145
+ help="Single or list of hosts, separated by comma.",
2146
+ )
2147
+ @click.option(
2148
+ "--ssh-user",
2149
+ "-U",
2150
+ required=False,
2151
+ type=str,
2152
+ default=None,
2153
+ help="Username of the SSH user.",
2154
+ )
2155
+ @click.option(
2156
+ "--ssh-key",
2157
+ "-K",
2158
+ required=False,
2159
+ type=str,
2160
+ default=None,
2161
+ help="Path to the SSH key file.",
2162
+ )
2163
+ @click.option(
2164
+ "--docker",
2165
+ "-d",
2166
+ required=False,
2167
+ type=str,
2168
+ default=None,
2169
+ help="Name of the docker container, if applicable.",
2170
+ )
2171
+ @click.option(
2172
+ "--local",
2173
+ "-L",
2174
+ required=False,
2175
+ type=bool,
2176
+ is_flag=True,
2177
+ default=None,
2178
+ help="Also include information about the local node.",
2179
+ )
2180
+ @click.option(
2181
+ "--output", "-o", required=False, type=str, default=None, help="Output file."
2182
+ )
2183
+ @click.option(
2184
+ "--logs/--no-logs",
2185
+ is_flag=True,
2186
+ default=True,
2187
+ help="Collect logs from ray session dir",
2188
+ )
2189
+ @click.option(
2190
+ "--debug-state/--no-debug-state",
2191
+ is_flag=True,
2192
+ default=True,
2193
+ help="Collect debug_state.txt from ray log dir",
2194
+ )
2195
+ @click.option(
2196
+ "--pip/--no-pip", is_flag=True, default=True, help="Collect installed pip packages"
2197
+ )
2198
+ @click.option(
2199
+ "--processes/--no-processes",
2200
+ is_flag=True,
2201
+ default=True,
2202
+ help="Collect info on running processes",
2203
+ )
2204
+ @click.option(
2205
+ "--processes-verbose/--no-processes-verbose",
2206
+ is_flag=True,
2207
+ default=True,
2208
+ help="Increase process information verbosity",
2209
+ )
2210
+ @click.option(
2211
+ "--tempfile",
2212
+ "-T",
2213
+ required=False,
2214
+ type=str,
2215
+ default=None,
2216
+ help="Temporary file to use",
2217
+ )
2218
+ def cluster_dump(
2219
+ cluster_config_file: Optional[str] = None,
2220
+ host: Optional[str] = None,
2221
+ ssh_user: Optional[str] = None,
2222
+ ssh_key: Optional[str] = None,
2223
+ docker: Optional[str] = None,
2224
+ local: Optional[bool] = None,
2225
+ output: Optional[str] = None,
2226
+ logs: bool = True,
2227
+ debug_state: bool = True,
2228
+ pip: bool = True,
2229
+ processes: bool = True,
2230
+ processes_verbose: bool = False,
2231
+ tempfile: Optional[str] = None,
2232
+ ):
2233
+ """Get log data from one or more nodes.
2234
+
2235
+ Best used with Ray cluster configs:
2236
+
2237
+ ray cluster-dump [cluster.yaml]
2238
+
2239
+ Include the --local flag to also collect and include data from the
2240
+ local node.
2241
+
2242
+ Missing fields will be tried to be auto-filled.
2243
+
2244
+ You can also manually specify a list of hosts using the
2245
+ ``--host <host1,host2,...>`` parameter.
2246
+ """
2247
+ archive_path = get_cluster_dump_archive(
2248
+ cluster_config_file=cluster_config_file,
2249
+ host=host,
2250
+ ssh_user=ssh_user,
2251
+ ssh_key=ssh_key,
2252
+ docker=docker,
2253
+ local=local,
2254
+ output=output,
2255
+ logs=logs,
2256
+ debug_state=debug_state,
2257
+ pip=pip,
2258
+ processes=processes,
2259
+ processes_verbose=processes_verbose,
2260
+ tempfile=tempfile,
2261
+ )
2262
+ if archive_path:
2263
+ click.echo(f"Created archive: {archive_path}")
2264
+ else:
2265
+ click.echo("Could not create archive.")
2266
+
2267
+
2268
+ @cli.command(hidden=True)
2269
+ @click.option(
2270
+ "--address", required=False, type=str, help="Override the address to connect to."
2271
+ )
2272
+ def global_gc(address):
2273
+ """Trigger Python garbage collection on all cluster workers."""
2274
+ ray.init(address=address)
2275
+ ray._private.internal_api.global_gc()
2276
+ print("Triggered gc.collect() on all workers.")
2277
+
2278
+
2279
+ @cli.command(hidden=True)
2280
+ @click.option(
2281
+ "--address", required=False, type=str, help="Override the address to connect to."
2282
+ )
2283
+ @click.option(
2284
+ "--node-id",
2285
+ required=True,
2286
+ type=str,
2287
+ help="Hex ID of the worker node to be drained.",
2288
+ )
2289
+ @click.option(
2290
+ "--reason",
2291
+ required=True,
2292
+ type=click.Choice(
2293
+ [
2294
+ item[0]
2295
+ for item in autoscaler_pb2.DrainNodeReason.items()
2296
+ if item[1] != autoscaler_pb2.DRAIN_NODE_REASON_UNSPECIFIED
2297
+ ]
2298
+ ),
2299
+ help="The reason why the node will be drained.",
2300
+ )
2301
+ @click.option(
2302
+ "--reason-message",
2303
+ required=True,
2304
+ type=str,
2305
+ help="The detailed drain reason message.",
2306
+ )
2307
+ @click.option(
2308
+ "--deadline-remaining-seconds",
2309
+ required=False,
2310
+ type=int,
2311
+ default=None,
2312
+ help="Inform GCS that the node to be drained will be force killed "
2313
+ "after this many of seconds. "
2314
+ "Default is None which means there is no deadline. "
2315
+ "Note: This command doesn't actually force kill the node after the deadline, "
2316
+ "it's the caller's responsibility to do that.",
2317
+ )
2318
+ def drain_node(
2319
+ address: str,
2320
+ node_id: str,
2321
+ reason: str,
2322
+ reason_message: str,
2323
+ deadline_remaining_seconds: int,
2324
+ ):
2325
+ """
2326
+ This is NOT a public API.
2327
+
2328
+ Manually drain a worker node.
2329
+ """
2330
+ deadline_timestamp_ms = 0
2331
+ if deadline_remaining_seconds is not None:
2332
+ if deadline_remaining_seconds < 0:
2333
+ raise click.BadParameter(
2334
+ "--deadline-remaining-seconds cannot be negative, "
2335
+ f"got {deadline_remaining_seconds}"
2336
+ )
2337
+ deadline_timestamp_ms = (time.time_ns() // 1000000) + (
2338
+ deadline_remaining_seconds * 1000
2339
+ )
2340
+
2341
+ if ray.NodeID.from_hex(node_id) == ray.NodeID.nil():
2342
+ raise click.BadParameter(f"Invalid hex ID of a Ray node, got {node_id}")
2343
+
2344
+ address = services.canonicalize_bootstrap_address_or_die(address)
2345
+
2346
+ gcs_client = ray._raylet.GcsClient(address=address)
2347
+ _check_ray_version(gcs_client)
2348
+ is_accepted, rejection_error_message = gcs_client.drain_node(
2349
+ node_id,
2350
+ autoscaler_pb2.DrainNodeReason.Value(reason),
2351
+ reason_message,
2352
+ deadline_timestamp_ms,
2353
+ )
2354
+
2355
+ if not is_accepted:
2356
+ raise click.ClickException(
2357
+ f"The drain request is not accepted: {rejection_error_message}"
2358
+ )
2359
+
2360
+
2361
+ @cli.command(name="kuberay-autoscaler", hidden=True)
2362
+ @click.option(
2363
+ "--cluster-name",
2364
+ required=True,
2365
+ type=str,
2366
+ help="The name of the Ray Cluster.\n"
2367
+ "Should coincide with the `metadata.name` of the RayCluster CR.",
2368
+ )
2369
+ @click.option(
2370
+ "--cluster-namespace",
2371
+ required=True,
2372
+ type=str,
2373
+ help="The Kubernetes namespace the Ray Cluster lives in.\n"
2374
+ "Should coincide with the `metadata.namespace` of the RayCluster CR.",
2375
+ )
2376
+ def kuberay_autoscaler(cluster_name: str, cluster_namespace: str) -> None:
2377
+ """Runs the autoscaler for a Ray cluster managed by the KubeRay operator.
2378
+
2379
+ `ray kuberay-autoscaler` is meant to be used as an entry point in
2380
+ KubeRay cluster configs.
2381
+ `ray kuberay-autoscaler` is NOT a public CLI.
2382
+ """
2383
+ # Delay import to avoid introducing Ray core dependency on the Python Kubernetes
2384
+ # client.
2385
+ from ray.autoscaler._private.kuberay.run_autoscaler import run_kuberay_autoscaler
2386
+
2387
+ run_kuberay_autoscaler(cluster_name, cluster_namespace)
2388
+
2389
+
2390
+ @cli.command(name="health-check", hidden=True)
2391
+ @click.option(
2392
+ "--address", required=False, type=str, help="Override the address to connect to."
2393
+ )
2394
+ @click.option(
2395
+ "--redis_password",
2396
+ required=False,
2397
+ type=str,
2398
+ default=ray_constants.REDIS_DEFAULT_PASSWORD,
2399
+ help="Connect to ray with redis_password.",
2400
+ )
2401
+ @click.option(
2402
+ "--component",
2403
+ required=False,
2404
+ type=str,
2405
+ help="Health check for a specific component. Currently supports: "
2406
+ "[ray_client_server]",
2407
+ )
2408
+ @click.option(
2409
+ "--skip-version-check",
2410
+ is_flag=True,
2411
+ default=False,
2412
+ help="Skip comparison of GCS version with local Ray version.",
2413
+ )
2414
+ def healthcheck(address, redis_password, component, skip_version_check):
2415
+ """
2416
+ This is NOT a public API.
2417
+
2418
+ Health check a Ray or a specific component. Exit code 0 is healthy.
2419
+ """
2420
+
2421
+ address = services.canonicalize_bootstrap_address_or_die(address)
2422
+ gcs_client = ray._raylet.GcsClient(address=address)
2423
+ if not skip_version_check:
2424
+ _check_ray_version(gcs_client)
2425
+
2426
+ if not component:
2427
+ sys.exit(0)
2428
+
2429
+ report_str = gcs_client.internal_kv_get(
2430
+ component.encode(), namespace=ray_constants.KV_NAMESPACE_HEALTHCHECK
2431
+ )
2432
+ if not report_str:
2433
+ # Status was never updated
2434
+ sys.exit(1)
2435
+
2436
+ report = json.loads(report_str)
2437
+
2438
+ # TODO (Alex): We probably shouldn't rely on time here, but cloud providers
2439
+ # have very well synchronized NTP servers, so this should be fine in
2440
+ # practice.
2441
+ cur_time = time.time()
2442
+ report_time = float(report["time"])
2443
+
2444
+ # If the status is too old, the service has probably already died.
2445
+ delta = cur_time - report_time
2446
+ time_ok = delta < ray._private.ray_constants.HEALTHCHECK_EXPIRATION_S
2447
+
2448
+ if time_ok:
2449
+ sys.exit(0)
2450
+ else:
2451
+ sys.exit(1)
2452
+
2453
+
2454
+ @cli.command()
2455
+ @click.option("-v", "--verbose", is_flag=True)
2456
+ @click.option(
2457
+ "--dryrun",
2458
+ is_flag=True,
2459
+ help="Identifies the wheel but does not execute the installation.",
2460
+ )
2461
+ def install_nightly(verbose, dryrun):
2462
+ """Install the latest wheels for Ray.
2463
+
2464
+ This uses the same python environment as the one that Ray is currently
2465
+ installed in. Make sure that there is no Ray processes on this
2466
+ machine (ray stop) when running this command.
2467
+ """
2468
+ raydir = os.path.abspath(os.path.dirname(ray.__file__))
2469
+ all_wheels_path = os.path.join(raydir, "nightly-wheels.yaml")
2470
+
2471
+ wheels = None
2472
+ if os.path.exists(all_wheels_path):
2473
+ with open(all_wheels_path) as f:
2474
+ wheels = yaml.safe_load(f)
2475
+
2476
+ if not wheels:
2477
+ raise click.ClickException(
2478
+ f"Wheels not found in '{all_wheels_path}'! "
2479
+ "Please visit https://docs.ray.io/en/master/installation.html to "
2480
+ "obtain the latest wheels."
2481
+ )
2482
+
2483
+ platform = sys.platform
2484
+ py_version = "{0}.{1}".format(*sys.version_info[:2])
2485
+
2486
+ matching_wheel = None
2487
+ for target_platform, wheel_map in wheels.items():
2488
+ if verbose:
2489
+ print(f"Evaluating os={target_platform}, python={list(wheel_map)}")
2490
+ if platform.startswith(target_platform):
2491
+ if py_version in wheel_map:
2492
+ matching_wheel = wheel_map[py_version]
2493
+ break
2494
+ if verbose:
2495
+ print("Not matched.")
2496
+
2497
+ if matching_wheel is None:
2498
+ raise click.ClickException(
2499
+ "Unable to identify a matching platform. "
2500
+ "Please visit https://docs.ray.io/en/master/installation.html to "
2501
+ "obtain the latest wheels."
2502
+ )
2503
+ if dryrun:
2504
+ print(f"Found wheel: {matching_wheel}")
2505
+ else:
2506
+ cmd = [sys.executable, "-m", "pip", "install", "-U", matching_wheel]
2507
+ print(f"Running: {' '.join(cmd)}.")
2508
+ subprocess.check_call(cmd)
2509
+
2510
+
2511
+ @cli.command()
2512
+ @click.option(
2513
+ "--show-library-path",
2514
+ "-show",
2515
+ required=False,
2516
+ is_flag=True,
2517
+ help="Show the cpp include path and library path, if provided.",
2518
+ )
2519
+ @click.option(
2520
+ "--generate-bazel-project-template-to",
2521
+ "-gen",
2522
+ required=False,
2523
+ type=str,
2524
+ help="The directory to generate the bazel project template to, if provided.",
2525
+ )
2526
+ @add_click_logging_options
2527
+ def cpp(show_library_path, generate_bazel_project_template_to):
2528
+ """Show the cpp library path and generate the bazel project template."""
2529
+ if sys.platform == "win32":
2530
+ cli_logger.error("Ray C++ API is not supported on Windows currently.")
2531
+ sys.exit(1)
2532
+ if not show_library_path and not generate_bazel_project_template_to:
2533
+ raise ValueError(
2534
+ "Please input at least one option of '--show-library-path'"
2535
+ " and '--generate-bazel-project-template-to'."
2536
+ )
2537
+ raydir = os.path.abspath(os.path.dirname(ray.__file__))
2538
+ cpp_dir = os.path.join(raydir, "cpp")
2539
+ cpp_templete_dir = os.path.join(cpp_dir, "example")
2540
+ include_dir = os.path.join(cpp_dir, "include")
2541
+ lib_dir = os.path.join(cpp_dir, "lib")
2542
+ if not os.path.isdir(cpp_dir):
2543
+ raise ValueError('Please install ray with C++ API by "pip install ray[cpp]".')
2544
+ if show_library_path:
2545
+ cli_logger.print("Ray C++ include path {} ", cf.bold(f"{include_dir}"))
2546
+ cli_logger.print("Ray C++ library path {} ", cf.bold(f"{lib_dir}"))
2547
+ if generate_bazel_project_template_to:
2548
+ # copytree expects that the dst dir doesn't exist
2549
+ # so we manually delete it if it exists.
2550
+ if os.path.exists(generate_bazel_project_template_to):
2551
+ shutil.rmtree(generate_bazel_project_template_to)
2552
+ shutil.copytree(cpp_templete_dir, generate_bazel_project_template_to)
2553
+ out_include_dir = os.path.join(
2554
+ generate_bazel_project_template_to, "thirdparty/include"
2555
+ )
2556
+ if os.path.exists(out_include_dir):
2557
+ shutil.rmtree(out_include_dir)
2558
+ shutil.copytree(include_dir, out_include_dir)
2559
+ out_lib_dir = os.path.join(generate_bazel_project_template_to, "thirdparty/lib")
2560
+ if os.path.exists(out_lib_dir):
2561
+ shutil.rmtree(out_lib_dir)
2562
+ shutil.copytree(lib_dir, out_lib_dir)
2563
+
2564
+ cli_logger.print(
2565
+ "Project template generated to {}",
2566
+ cf.bold(f"{os.path.abspath(generate_bazel_project_template_to)}"),
2567
+ )
2568
+ cli_logger.print("To build and run this template, run")
2569
+ cli_logger.print(
2570
+ cf.bold(
2571
+ f" cd {os.path.abspath(generate_bazel_project_template_to)}"
2572
+ " && bash run.sh"
2573
+ )
2574
+ )
2575
+
2576
+
2577
+ @click.group(name="metrics")
2578
+ def metrics_group():
2579
+ pass
2580
+
2581
+
2582
+ @metrics_group.command(name="launch-prometheus")
2583
+ def launch_prometheus():
2584
+ install_and_start_prometheus.main()
2585
+
2586
+
2587
+ @metrics_group.command(name="shutdown-prometheus")
2588
+ def shutdown_prometheus():
2589
+ try:
2590
+ requests.post("http://localhost:9090/-/quit")
2591
+ except requests.exceptions.RequestException as e:
2592
+ print(f"An error occurred: {e}")
2593
+ sys.exit(1)
2594
+
2595
+
2596
+ def add_command_alias(command, name, hidden):
2597
+ new_command = copy.deepcopy(command)
2598
+ new_command.hidden = hidden
2599
+ cli.add_command(new_command, name=name)
2600
+
2601
+
2602
+ cli.add_command(dashboard)
2603
+ cli.add_command(debug)
2604
+ cli.add_command(start)
2605
+ cli.add_command(stop)
2606
+ cli.add_command(up)
2607
+ add_command_alias(up, name="create_or_update", hidden=True)
2608
+ cli.add_command(attach)
2609
+ cli.add_command(exec)
2610
+ add_command_alias(exec, name="exec_cmd", hidden=True)
2611
+ add_command_alias(rsync_down, name="rsync_down", hidden=True)
2612
+ add_command_alias(rsync_up, name="rsync_up", hidden=True)
2613
+ cli.add_command(submit)
2614
+ cli.add_command(down)
2615
+ add_command_alias(down, name="teardown", hidden=True)
2616
+ cli.add_command(kill_random_node)
2617
+ add_command_alias(get_head_ip, name="get_head_ip", hidden=True)
2618
+ cli.add_command(get_worker_ips)
2619
+ cli.add_command(microbenchmark)
2620
+ cli.add_command(stack)
2621
+ cli.add_command(status)
2622
+ cli.add_command(memory)
2623
+ cli.add_command(local_dump)
2624
+ cli.add_command(cluster_dump)
2625
+ cli.add_command(global_gc)
2626
+ cli.add_command(timeline)
2627
+ cli.add_command(install_nightly)
2628
+ cli.add_command(cpp)
2629
+ cli.add_command(disable_usage_stats)
2630
+ cli.add_command(enable_usage_stats)
2631
+ cli.add_command(metrics_group)
2632
+ cli.add_command(drain_node)
2633
+ cli.add_command(check_open_ports)
2634
+
2635
+ try:
2636
+ from ray.util.state.state_cli import (
2637
+ ray_get,
2638
+ ray_list,
2639
+ logs_state_cli_group,
2640
+ summary_state_cli_group,
2641
+ )
2642
+
2643
+ cli.add_command(ray_list, name="list")
2644
+ cli.add_command(ray_get, name="get")
2645
+ add_command_alias(summary_state_cli_group, name="summary", hidden=False)
2646
+ add_command_alias(logs_state_cli_group, name="logs", hidden=False)
2647
+ except ImportError as e:
2648
+ logger.debug(f"Integrating ray state command line tool failed: {e}")
2649
+
2650
+
2651
+ try:
2652
+ from ray.dashboard.modules.job.cli import job_cli_group
2653
+
2654
+ add_command_alias(job_cli_group, name="job", hidden=False)
2655
+ except Exception as e:
2656
+ logger.debug(f"Integrating ray jobs command line tool failed with {e}")
2657
+
2658
+
2659
+ try:
2660
+ from ray.serve.scripts import serve_cli
2661
+
2662
+ cli.add_command(serve_cli)
2663
+ except Exception as e:
2664
+ logger.debug(f"Integrating ray serve command line tool failed with {e}")
2665
+
2666
+
2667
+ def main():
2668
+ return cli()
2669
+
2670
+
2671
+ if __name__ == "__main__":
2672
+ main()
vllm/lib/python3.10/site-packages/ray/train/__init__.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Try import ray[train] core requirements (defined in setup.py)
2
+ # isort: off
3
+ try:
4
+ import fsspec # noqa: F401
5
+ import pandas # noqa: F401
6
+ import pyarrow # noqa: F401
7
+ import requests # noqa: F401
8
+ except ImportError as exc:
9
+ raise ImportError(
10
+ "Can't import ray.train as some dependencies are missing. "
11
+ 'Run `pip install "ray[train]"` to fix.'
12
+ ) from exc
13
+ # isort: on
14
+
15
+
16
+ from ray._private.usage import usage_lib
17
+ from ray.air.config import CheckpointConfig, FailureConfig, RunConfig, ScalingConfig
18
+ from ray.air.result import Result
19
+
20
+ # Import this first so it can be used in other modules
21
+ from ray.train._checkpoint import Checkpoint
22
+ from ray.train._internal.data_config import DataConfig
23
+ from ray.train._internal.session import get_checkpoint, get_dataset_shard, report
24
+ from ray.train._internal.syncer import SyncConfig
25
+ from ray.train.backend import BackendConfig
26
+ from ray.train.constants import TRAIN_DATASET_KEY
27
+ from ray.train.context import get_context
28
+ from ray.train.trainer import TrainingIterator
29
+
30
+ usage_lib.record_library_usage("train")
31
+
32
+ Checkpoint.__module__ = "ray.train"
33
+
34
+ __all__ = [
35
+ "get_checkpoint",
36
+ "get_context",
37
+ "get_dataset_shard",
38
+ "report",
39
+ "BackendConfig",
40
+ "Checkpoint",
41
+ "CheckpointConfig",
42
+ "DataConfig",
43
+ "FailureConfig",
44
+ "Result",
45
+ "RunConfig",
46
+ "ScalingConfig",
47
+ "SyncConfig",
48
+ "TrainingIterator",
49
+ "TRAIN_DATASET_KEY",
50
+ ]
51
+
52
+ get_checkpoint.__module__ = "ray.train"
53
+ get_context.__module__ = "ray.train"
54
+ get_dataset_shard.__module__ = "ray.train"
55
+ report.__module__ = "ray.train"
56
+ BackendConfig.__module__ = "ray.train"
57
+ Checkpoint.__module__ = "ray.train"
58
+ CheckpointConfig.__module__ = "ray.train"
59
+ DataConfig.__module__ = "ray.train"
60
+ FailureConfig.__module__ = "ray.train"
61
+ Result.__module__ = "ray.train"
62
+ RunConfig.__module__ = "ray.train"
63
+ ScalingConfig.__module__ = "ray.train"
64
+ SyncConfig.__module__ = "ray.train"
65
+ TrainingIterator.__module__ = "ray.train"
vllm/lib/python3.10/site-packages/ray/train/_checkpoint.py ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import glob
3
+ import json
4
+ import logging
5
+ import os
6
+ import platform
7
+ import shutil
8
+ import tempfile
9
+ import traceback
10
+ import uuid
11
+ from pathlib import Path
12
+ from typing import Any, Dict, Iterator, List, Optional, Union
13
+
14
+ import pyarrow.fs
15
+
16
+ from ray.air._internal.filelock import TempFileLock
17
+ from ray.train._internal.storage import _download_from_fs_path, _exists_at_fs_path
18
+ from ray.util.annotations import PublicAPI
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ # The filename of the file that stores user metadata set on the checkpoint.
23
+ _METADATA_FILE_NAME = ".metadata.json"
24
+
25
+ # The prefix of the temp checkpoint directory that `to_directory` downloads to
26
+ # on the local filesystem.
27
+ _CHECKPOINT_TEMP_DIR_PREFIX = "checkpoint_tmp_"
28
+
29
+
30
+ class _CheckpointMetaClass(type):
31
+ def __getattr__(self, item):
32
+ try:
33
+ return super().__getattribute__(item)
34
+ except AttributeError as exc:
35
+ if item in {
36
+ "from_dict",
37
+ "to_dict",
38
+ "from_bytes",
39
+ "to_bytes",
40
+ "get_internal_representation",
41
+ }:
42
+ raise _get_migration_error(item) from exc
43
+ elif item in {
44
+ "from_uri",
45
+ "to_uri",
46
+ "uri",
47
+ }:
48
+ raise _get_uri_error(item) from exc
49
+ elif item in {"get_preprocessor", "set_preprocessor"}:
50
+ raise _get_preprocessor_error(item) from exc
51
+
52
+ raise exc
53
+
54
+
55
+ @PublicAPI(stability="beta")
56
+ class Checkpoint(metaclass=_CheckpointMetaClass):
57
+ """A reference to data persisted as a directory in local or remote storage.
58
+
59
+ Access the checkpoint contents locally using ``checkpoint.to_directory()``
60
+ or ``checkpoint.as_directory``.
61
+
62
+ Attributes
63
+ ----------
64
+ path: A path on the filesystem containing the checkpoint contents.
65
+ filesystem: PyArrow FileSystem that can be used to access data at the `path`.
66
+
67
+ See Also
68
+ --------
69
+ ray.train.report : Report a checkpoint during training (with Ray Train/Tune).
70
+ ray.train.get_checkpoint : Get the latest checkpoint during training
71
+ (for restoration).
72
+
73
+ :ref:`train-checkpointing`
74
+ :ref:`persistent-storage-guide`
75
+
76
+ Examples
77
+ --------
78
+
79
+ Creating a checkpoint using ``Checkpoint.from_directory``:
80
+
81
+ >>> from ray.train import Checkpoint
82
+ >>> checkpoint = Checkpoint.from_directory("/tmp/example_checkpoint_dir")
83
+ >>> checkpoint.filesystem # doctest: +ELLIPSIS
84
+ <pyarrow._fs.LocalFileSystem object...
85
+ >>> checkpoint.path
86
+ '/tmp/example_checkpoint_dir'
87
+
88
+ Creating a checkpoint from a remote URI:
89
+
90
+ >>> checkpoint = Checkpoint("s3://bucket/path/to/checkpoint")
91
+ >>> checkpoint.filesystem # doctest: +ELLIPSIS
92
+ <pyarrow._s3fs.S3FileSystem object...
93
+ >>> checkpoint.path
94
+ 'bucket/path/to/checkpoint'
95
+
96
+ Creating a checkpoint with a custom filesystem:
97
+
98
+ >>> checkpoint = Checkpoint(
99
+ ... path="bucket/path/to/checkpoint",
100
+ ... filesystem=pyarrow.fs.S3FileSystem(),
101
+ ... )
102
+ >>> checkpoint.filesystem # doctest: +ELLIPSIS
103
+ <pyarrow._s3fs.S3FileSystem object...
104
+ >>> checkpoint.path
105
+ 'bucket/path/to/checkpoint'
106
+
107
+ Accessing a checkpoint's contents:
108
+
109
+ >>> import os # doctest: +SKIP
110
+ >>> with checkpoint.as_directory() as local_checkpoint_dir: # doctest: +SKIP
111
+ ... print(os.listdir(local_checkpoint_dir)) # doctest: +SKIP
112
+ ['model.pt', 'optimizer.pt', 'misc.pt']
113
+ """
114
+
115
+ def __init__(
116
+ self,
117
+ path: Union[str, os.PathLike],
118
+ filesystem: Optional["pyarrow.fs.FileSystem"] = None,
119
+ ):
120
+ """Construct a Checkpoint.
121
+
122
+ Args:
123
+ path: A local path or remote URI containing the checkpoint data.
124
+ If a filesystem is provided, then this path must NOT be a URI.
125
+ It should be a path on the filesystem with the prefix already stripped.
126
+ filesystem: PyArrow FileSystem to use to access data at the path.
127
+ If not specified, this is inferred from the URI scheme.
128
+ """
129
+ self.path = str(path)
130
+ self.filesystem = filesystem
131
+
132
+ if path and not filesystem:
133
+ self.filesystem, self.path = pyarrow.fs.FileSystem.from_uri(path)
134
+
135
+ # This random UUID is used to create a temporary directory name on the
136
+ # local filesystem, which will be used for downloading checkpoint data.
137
+ # This ensures that if multiple processes download the same checkpoint object
138
+ # only one process performs the actual download while the others wait.
139
+ # This prevents duplicated download efforts and data.
140
+ # NOTE: Calling `to_directory` from multiple `Checkpoint` objects
141
+ # that point to the same (fs, path) will still download the data multiple times.
142
+ # This only ensures a canonical temp directory name for a single `Checkpoint`.
143
+ self._uuid = uuid.uuid4()
144
+
145
+ def __repr__(self):
146
+ return f"Checkpoint(filesystem={self.filesystem.type_name}, path={self.path})"
147
+
148
+ def get_metadata(self) -> Dict[str, Any]:
149
+ """Return the metadata dict stored with the checkpoint.
150
+
151
+ If no metadata is stored, an empty dict is returned.
152
+ """
153
+ metadata_path = Path(self.path, _METADATA_FILE_NAME).as_posix()
154
+ if not _exists_at_fs_path(self.filesystem, metadata_path):
155
+ return {}
156
+
157
+ with self.filesystem.open_input_file(metadata_path) as f:
158
+ return json.loads(f.readall().decode("utf-8"))
159
+
160
+ def set_metadata(self, metadata: Dict[str, Any]) -> None:
161
+ """Set the metadata stored with this checkpoint.
162
+
163
+ This will overwrite any existing metadata stored with this checkpoint.
164
+ """
165
+ metadata_path = Path(self.path, _METADATA_FILE_NAME).as_posix()
166
+ with self.filesystem.open_output_stream(metadata_path) as f:
167
+ f.write(json.dumps(metadata).encode("utf-8"))
168
+
169
+ def update_metadata(self, metadata: Dict[str, Any]) -> None:
170
+ """Update the metadata stored with this checkpoint.
171
+
172
+ This will update any existing metadata stored with this checkpoint.
173
+ """
174
+ existing_metadata = self.get_metadata()
175
+ existing_metadata.update(metadata)
176
+ self.set_metadata(existing_metadata)
177
+
178
+ @classmethod
179
+ def from_directory(cls, path: Union[str, os.PathLike]) -> "Checkpoint":
180
+ """Create checkpoint object from a local directory.
181
+
182
+ Args:
183
+ path: Local directory containing checkpoint data.
184
+
185
+ Returns:
186
+ A ray.train.Checkpoint object.
187
+ """
188
+ return cls(path, filesystem=pyarrow.fs.LocalFileSystem())
189
+
190
+ def to_directory(self, path: Optional[Union[str, os.PathLike]] = None) -> str:
191
+ """Write checkpoint data to a local directory.
192
+
193
+ *If multiple processes on the same node call this method simultaneously,*
194
+ only a single process will perform the download, while the others
195
+ wait for the download to finish. Once the download finishes, all processes
196
+ receive the same local directory to read from.
197
+
198
+ Args:
199
+ path: Target directory to download data to. If not specified,
200
+ this method will use a temporary directory.
201
+
202
+ Returns:
203
+ str: Directory containing checkpoint data.
204
+ """
205
+ user_provided_path = path is not None
206
+ local_path = (
207
+ path if user_provided_path else self._get_temporary_checkpoint_dir()
208
+ )
209
+ local_path = os.path.normpath(os.path.expanduser(str(local_path)))
210
+ os.makedirs(local_path, exist_ok=True)
211
+
212
+ try:
213
+ # Timeout 0 means there will be only one attempt to acquire
214
+ # the file lock. If it cannot be acquired, throw a TimeoutError
215
+ with TempFileLock(local_path, timeout=0):
216
+ _download_from_fs_path(
217
+ fs=self.filesystem, fs_path=self.path, local_path=local_path
218
+ )
219
+ except TimeoutError:
220
+ # if the directory is already locked, then wait but do not do anything.
221
+ with TempFileLock(local_path, timeout=-1):
222
+ pass
223
+ if not os.path.exists(local_path):
224
+ raise RuntimeError(
225
+ f"Checkpoint directory {local_path} does not exist, "
226
+ "even though it should have been created by "
227
+ "another process. Please raise an issue on GitHub: "
228
+ "https://github.com/ray-project/ray/issues"
229
+ )
230
+
231
+ return local_path
232
+
233
+ @contextlib.contextmanager
234
+ def as_directory(self) -> Iterator[str]:
235
+ """Returns checkpoint contents in a local directory as a context.
236
+
237
+ This function makes checkpoint data available as a directory while avoiding
238
+ unnecessary copies and left-over temporary data.
239
+
240
+ *If the checkpoint points to a local directory*, this method just returns the
241
+ local directory path without making a copy, and nothing will be cleaned up
242
+ after exiting the context.
243
+
244
+ *If the checkpoint points to a remote directory*, this method will download the
245
+ checkpoint to a local temporary directory and return the path
246
+ to the temporary directory.
247
+
248
+ *If multiple processes on the same node call this method simultaneously,*
249
+ only a single process will perform the download, while the others
250
+ wait for the download to finish. Once the download finishes, all processes
251
+ receive the same local (temporary) directory to read from.
252
+
253
+ Once all processes have finished working with the checkpoint,
254
+ the temporary directory is cleaned up.
255
+
256
+ Users should treat the returned checkpoint directory as read-only and avoid
257
+ changing any data within it, as it may be deleted when exiting the context.
258
+
259
+ Example:
260
+
261
+ .. testcode::
262
+ :hide:
263
+
264
+ from pathlib import Path
265
+ import tempfile
266
+
267
+ from ray.train import Checkpoint
268
+
269
+ temp_dir = tempfile.mkdtemp()
270
+ (Path(temp_dir) / "example.txt").write_text("example checkpoint data")
271
+ checkpoint = Checkpoint.from_directory(temp_dir)
272
+
273
+ .. testcode::
274
+
275
+ with checkpoint.as_directory() as checkpoint_dir:
276
+ # Do some read-only processing of files within checkpoint_dir
277
+ pass
278
+
279
+ # At this point, if a temporary directory was created, it will have
280
+ # been deleted.
281
+
282
+ """
283
+ if isinstance(self.filesystem, pyarrow.fs.LocalFileSystem):
284
+ yield self.path
285
+ else:
286
+ del_lock_path = _get_del_lock_path(self._get_temporary_checkpoint_dir())
287
+ open(del_lock_path, "a").close()
288
+
289
+ temp_dir = self.to_directory()
290
+ try:
291
+ yield temp_dir
292
+ finally:
293
+ # Always cleanup the del lock after we're done with the directory.
294
+ # This avoids leaving a lock file behind in the case of an exception
295
+ # in the user code.
296
+ try:
297
+ os.remove(del_lock_path)
298
+ except Exception:
299
+ logger.warning(
300
+ f"Could not remove {del_lock_path} deletion file lock. "
301
+ f"Traceback:\n{traceback.format_exc()}"
302
+ )
303
+
304
+ # If there are no more lock files, that means there are no more
305
+ # readers of this directory, and we can safely delete it.
306
+ # In the edge case (process crash before del lock file is removed),
307
+ # we do not remove the directory at all.
308
+ # Since it's in /tmp, this is not that big of a deal.
309
+ # check if any lock files are remaining
310
+ remaining_locks = _list_existing_del_locks(temp_dir)
311
+ if not remaining_locks:
312
+ try:
313
+ # Timeout 0 means there will be only one attempt to acquire
314
+ # the file lock. If it cannot be acquired, a TimeoutError
315
+ # will be thrown.
316
+ with TempFileLock(temp_dir, timeout=0):
317
+ shutil.rmtree(temp_dir, ignore_errors=True)
318
+ except TimeoutError:
319
+ pass
320
+
321
+ def _get_temporary_checkpoint_dir(self) -> str:
322
+ """Return the name for the temporary checkpoint dir that this checkpoint
323
+ will get downloaded to, if accessing via `to_directory` or `as_directory`.
324
+ """
325
+ tmp_dir_path = tempfile.gettempdir()
326
+ checkpoint_dir_name = _CHECKPOINT_TEMP_DIR_PREFIX + self._uuid.hex
327
+ if platform.system() == "Windows":
328
+ # Max path on Windows is 260 chars, -1 for joining \
329
+ # Also leave a little for the del lock
330
+ del_lock_name = _get_del_lock_path("")
331
+ checkpoint_dir_name = (
332
+ _CHECKPOINT_TEMP_DIR_PREFIX
333
+ + self._uuid.hex[
334
+ -259
335
+ + len(_CHECKPOINT_TEMP_DIR_PREFIX)
336
+ + len(tmp_dir_path)
337
+ + len(del_lock_name) :
338
+ ]
339
+ )
340
+ if not checkpoint_dir_name.startswith(_CHECKPOINT_TEMP_DIR_PREFIX):
341
+ raise RuntimeError(
342
+ "Couldn't create checkpoint directory due to length "
343
+ "constraints. Try specifying a shorter checkpoint path."
344
+ )
345
+ return Path(tmp_dir_path, checkpoint_dir_name).as_posix()
346
+
347
+ def __fspath__(self):
348
+ raise TypeError(
349
+ "You cannot use `Checkpoint` objects directly as paths. "
350
+ "Use `Checkpoint.to_directory()` or `Checkpoint.as_directory()` instead."
351
+ )
352
+
353
+
354
+ def _get_del_lock_path(path: str, suffix: str = None) -> str:
355
+ """Get the path to the deletion lock file for a file/directory at `path`.
356
+
357
+ Example:
358
+
359
+ >>> _get_del_lock_path("/tmp/checkpoint_tmp") # doctest: +ELLIPSIS
360
+ '/tmp/checkpoint_tmp.del_lock_...
361
+ >>> _get_del_lock_path("/tmp/checkpoint_tmp/") # doctest: +ELLIPSIS
362
+ '/tmp/checkpoint_tmp.del_lock_...
363
+ >>> _get_del_lock_path("/tmp/checkpoint_tmp.txt") # doctest: +ELLIPSIS
364
+ '/tmp/checkpoint_tmp.txt.del_lock_...
365
+
366
+ """
367
+ suffix = suffix if suffix is not None else str(os.getpid())
368
+ return f"{path.rstrip('/')}.del_lock_{suffix}"
369
+
370
+
371
+ def _list_existing_del_locks(path: str) -> List[str]:
372
+ """List all the deletion lock files for a file/directory at `path`.
373
+
374
+ For example, if 2 checkpoints are being read via `as_directory`,
375
+ then this should return a list of 2 deletion lock files.
376
+ """
377
+ return list(glob.glob(f"{_get_del_lock_path(path, suffix='*')}"))
378
+
379
+
380
+ def _get_migration_error(name: str):
381
+ return AttributeError(
382
+ f"The new `ray.train.Checkpoint` class does not support `{name}()`. "
383
+ f"Instead, only directories are supported.\n\n"
384
+ f"Example to store a dictionary in a checkpoint:\n\n"
385
+ f"import os, tempfile\n"
386
+ f"import ray.cloudpickle as pickle\n"
387
+ f"from ray import train\n"
388
+ f"from ray.train import Checkpoint\n\n"
389
+ f"with tempfile.TemporaryDirectory() as checkpoint_dir:\n"
390
+ f" with open(os.path.join(checkpoint_dir, 'data.pkl'), 'wb') as fp:\n"
391
+ f" pickle.dump({{'data': 'value'}}, fp)\n\n"
392
+ f" checkpoint = Checkpoint.from_directory(checkpoint_dir)\n"
393
+ f" train.report(..., checkpoint=checkpoint)\n\n"
394
+ f"Example to load a dictionary from a checkpoint:\n\n"
395
+ f"if train.get_checkpoint():\n"
396
+ f" with train.get_checkpoint().as_directory() as checkpoint_dir:\n"
397
+ f" with open(os.path.join(checkpoint_dir, 'data.pkl'), 'rb') as fp:\n"
398
+ f" data = pickle.load(fp)"
399
+ )
400
+
401
+
402
+ def _get_uri_error(name: str):
403
+ return AttributeError(
404
+ f"The new `ray.train.Checkpoint` class does not support `{name}()`. "
405
+ f"To create a checkpoint from remote storage, create a `Checkpoint` using its "
406
+ f"constructor instead of `from_directory`.\n"
407
+ f'Example: `Checkpoint(path="s3://a/b/c")`.\n'
408
+ f"Then, access the contents of the checkpoint with "
409
+ f"`checkpoint.as_directory()` / `checkpoint.to_directory()`.\n"
410
+ f"To upload data to remote storage, use e.g. `pyarrow.fs.FileSystem` "
411
+ f"or your client of choice."
412
+ )
413
+
414
+
415
+ def _get_preprocessor_error(name: str):
416
+ return AttributeError(
417
+ f"The new `ray.train.Checkpoint` class does not support `{name}()`. "
418
+ f"To include preprocessor information in checkpoints, "
419
+ f"pass it as metadata in the <Framework>Trainer constructor.\n"
420
+ f"Example: `TorchTrainer(..., metadata={{...}})`.\n"
421
+ f"After training, access it in the checkpoint via `checkpoint.get_metadata()`. "
422
+ f"See here: https://docs.ray.io/en/master/train/user-guides/"
423
+ f"data-loading-preprocessing.html#preprocessing-structured-data"
424
+ )
vllm/lib/python3.10/site-packages/ray/train/backend.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from contextlib import nullcontext
3
+ from typing import TypeVar
4
+
5
+ from ray.train._internal.utils import Singleton
6
+ from ray.train._internal.worker_group import WorkerGroup
7
+ from ray.util.annotations import DeveloperAPI
8
+ from ray.widgets import make_table_html_repr
9
+
10
+ EncodedData = TypeVar("EncodedData")
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ @DeveloperAPI
16
+ class BackendConfig:
17
+ """Parent class for configurations of training backend."""
18
+
19
+ @property
20
+ def backend_cls(self):
21
+ return Backend
22
+
23
+ @property
24
+ def train_func_context(self):
25
+ return nullcontext
26
+
27
+ def _repr_html_(self) -> str:
28
+ return make_table_html_repr(obj=self, title=type(self).__name__)
29
+
30
+
31
+ @DeveloperAPI
32
+ class Backend(metaclass=Singleton):
33
+ """Singleton for distributed communication backend.
34
+
35
+ Attributes:
36
+ share_cuda_visible_devices: If True, each worker
37
+ process will have CUDA_VISIBLE_DEVICES set as the visible device
38
+ IDs of all workers on the same node for this training instance.
39
+ If False, each worker will have CUDA_VISIBLE_DEVICES set to the
40
+ device IDs allocated by Ray for that worker.
41
+ """
42
+
43
+ share_cuda_visible_devices: bool = False
44
+
45
+ def on_start(self, worker_group: WorkerGroup, backend_config: BackendConfig):
46
+ """Logic for starting this backend."""
47
+ pass
48
+
49
+ def on_shutdown(self, worker_group: WorkerGroup, backend_config: BackendConfig):
50
+ """Logic for shutting down the backend."""
51
+ pass
52
+
53
+ def on_training_start(
54
+ self, worker_group: WorkerGroup, backend_config: BackendConfig
55
+ ):
56
+ """Logic ran right before training is started.
57
+
58
+ Session API is available at this point."""
59
+ pass
vllm/lib/python3.10/site-packages/ray/train/constants.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ import ray
4
+ from ray.air.constants import ( # noqa: F401
5
+ COPY_DIRECTORY_CHECKPOINTS_INSTEAD_OF_MOVING_ENV,
6
+ EVALUATION_DATASET_KEY,
7
+ MODEL_KEY,
8
+ PREPROCESSOR_KEY,
9
+ TRAIN_DATASET_KEY,
10
+ )
11
+
12
+
13
+ def _get_ray_train_session_dir() -> str:
14
+ assert ray.is_initialized(), "Ray must be initialized to get the session dir."
15
+ return Path(
16
+ ray._private.worker._global_node.get_session_dir_path(), "artifacts"
17
+ ).as_posix()
18
+
19
+
20
+ DEFAULT_STORAGE_PATH = Path("~/ray_results").expanduser().as_posix()
21
+
22
+ # Autofilled ray.train.report() metrics. Keys should be consistent with Tune.
23
+ CHECKPOINT_DIR_NAME = "checkpoint_dir_name"
24
+ TIME_TOTAL_S = "_time_total_s"
25
+ WORKER_HOSTNAME = "_hostname"
26
+ WORKER_NODE_IP = "_node_ip"
27
+ WORKER_PID = "_pid"
28
+
29
+ # Will not be reported unless ENABLE_DETAILED_AUTOFILLED_METRICS_ENV
30
+ # env var is not 0
31
+ DETAILED_AUTOFILLED_KEYS = {WORKER_HOSTNAME, WORKER_NODE_IP, WORKER_PID, TIME_TOTAL_S}
32
+
33
+ # Default filename for JSON logger
34
+ RESULT_FILE_JSON = "results.json"
35
+
36
+ # The name of the subdirectory inside the trainer run_dir to store checkpoints.
37
+ TRAIN_CHECKPOINT_SUBDIR = "checkpoints"
38
+
39
+ # The key to use to specify the checkpoint id for Tune.
40
+ # This needs to be added to the checkpoint dictionary so if the Tune trial
41
+ # is restarted, the checkpoint_id can continue to increment.
42
+ TUNE_CHECKPOINT_ID = "_current_checkpoint_id"
43
+
44
+ # Deprecated configs can use this value to detect if the user has set it.
45
+ _DEPRECATED_VALUE = "DEPRECATED"
46
+
47
+ # ==================================================
48
+ # Environment Variables
49
+ # ==================================================
50
+
51
+ ENABLE_DETAILED_AUTOFILLED_METRICS_ENV = (
52
+ "TRAIN_RESULT_ENABLE_DETAILED_AUTOFILLED_METRICS"
53
+ )
54
+
55
+ # Integer value which if set will override the value of
56
+ # Backend.share_cuda_visible_devices. 1 for True, 0 for False.
57
+ ENABLE_SHARE_CUDA_VISIBLE_DEVICES_ENV = "TRAIN_ENABLE_SHARE_CUDA_VISIBLE_DEVICES"
58
+
59
+ # Integer value which if set will not share neuron-core accelerator visible cores
60
+ # across workers. 1 for True (default), 0 for False.
61
+ ENABLE_SHARE_NEURON_CORES_ACCELERATOR_ENV = (
62
+ "TRAIN_ENABLE_SHARE_NEURON_CORES_ACCELERATOR"
63
+ )
64
+
65
+ # Integer value which if set will not share npu visible devices
66
+ # across workers. 1 for True (default), 0 for False.
67
+ ENABLE_SHARE_NPU_RT_VISIBLE_DEVICES_ENV = "TRAIN_ENABLE_SHARE_ASCEND_RT_VISIBLE_DEVICES"
68
+
69
+ # Integer value which indicates the number of seconds to wait when creating
70
+ # the worker placement group before timing out.
71
+ TRAIN_PLACEMENT_GROUP_TIMEOUT_S_ENV = "TRAIN_PLACEMENT_GROUP_TIMEOUT_S"
72
+
73
+ # Integer value which if set will change the placement group strategy from
74
+ # PACK to SPREAD. 1 for True, 0 for False.
75
+ TRAIN_ENABLE_WORKER_SPREAD_ENV = "TRAIN_ENABLE_WORKER_SPREAD"
76
+
77
+ # Set this to 0 to disable changing the working directory of each Tune Trainable
78
+ # or Train worker to the trial directory. Defaults to 1.
79
+ RAY_CHDIR_TO_TRIAL_DIR = "RAY_CHDIR_TO_TRIAL_DIR"
80
+
81
+ # Set this to 1 to count preemption errors toward `FailureConfig(max_failures)`.
82
+ # Defaults to 0, which always retries on node preemption failures.
83
+ RAY_TRAIN_COUNT_PREEMPTION_AS_FAILURE = "RAY_TRAIN_COUNT_PREEMPTION_AS_FAILURE"
84
+
85
+ # Set this to 1 to start a StateActor and collect information Train Runs
86
+ # Defaults to 0
87
+ RAY_TRAIN_ENABLE_STATE_TRACKING = "RAY_TRAIN_ENABLE_STATE_TRACKING"
88
+
89
+ # NOTE: When adding a new environment variable, please track it in this list.
90
+ TRAIN_ENV_VARS = {
91
+ ENABLE_DETAILED_AUTOFILLED_METRICS_ENV,
92
+ ENABLE_SHARE_CUDA_VISIBLE_DEVICES_ENV,
93
+ ENABLE_SHARE_NEURON_CORES_ACCELERATOR_ENV,
94
+ TRAIN_PLACEMENT_GROUP_TIMEOUT_S_ENV,
95
+ TRAIN_ENABLE_WORKER_SPREAD_ENV,
96
+ RAY_CHDIR_TO_TRIAL_DIR,
97
+ RAY_TRAIN_COUNT_PREEMPTION_AS_FAILURE,
98
+ RAY_TRAIN_ENABLE_STATE_TRACKING,
99
+ }
100
+
101
+ # Key for AIR Checkpoint metadata in TrainingResult metadata
102
+ CHECKPOINT_METADATA_KEY = "checkpoint_metadata"
103
+
104
+ # Key for AIR Checkpoint world rank in TrainingResult metadata
105
+ CHECKPOINT_RANK_KEY = "checkpoint_rank"
vllm/lib/python3.10/site-packages/ray/train/context.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import threading
2
+ from typing import TYPE_CHECKING, Any, Dict, Optional
3
+
4
+ from ray.train._internal import session
5
+ from ray.train._internal.storage import StorageContext
6
+ from ray.util.annotations import DeveloperAPI, PublicAPI
7
+
8
+ if TYPE_CHECKING:
9
+ from ray.tune.execution.placement_groups import PlacementGroupFactory
10
+
11
+
12
+ # The context singleton on this process.
13
+ _default_context: "Optional[TrainContext]" = None
14
+ _context_lock = threading.Lock()
15
+
16
+
17
+ def _copy_doc(copy_func):
18
+ def wrapped(func):
19
+ func.__doc__ = copy_func.__doc__
20
+ return func
21
+
22
+ return wrapped
23
+
24
+
25
+ @PublicAPI(stability="stable")
26
+ class TrainContext:
27
+ """Context for Ray training executions."""
28
+
29
+ @_copy_doc(session.get_metadata)
30
+ def get_metadata(self) -> Dict[str, Any]:
31
+ return session.get_metadata()
32
+
33
+ @_copy_doc(session.get_experiment_name)
34
+ def get_experiment_name(self) -> str:
35
+ return session.get_experiment_name()
36
+
37
+ @_copy_doc(session.get_trial_name)
38
+ def get_trial_name(self) -> str:
39
+ return session.get_trial_name()
40
+
41
+ @_copy_doc(session.get_trial_id)
42
+ def get_trial_id(self) -> str:
43
+ return session.get_trial_id()
44
+
45
+ @_copy_doc(session.get_trial_resources)
46
+ def get_trial_resources(self) -> "PlacementGroupFactory":
47
+ return session.get_trial_resources()
48
+
49
+ @_copy_doc(session.get_trial_dir)
50
+ def get_trial_dir(self) -> str:
51
+ return session.get_trial_dir()
52
+
53
+ @_copy_doc(session.get_world_size)
54
+ def get_world_size(self) -> int:
55
+ return session.get_world_size()
56
+
57
+ @_copy_doc(session.get_world_rank)
58
+ def get_world_rank(self) -> int:
59
+ return session.get_world_rank()
60
+
61
+ @_copy_doc(session.get_local_rank)
62
+ def get_local_rank(self) -> int:
63
+ return session.get_local_rank()
64
+
65
+ @_copy_doc(session.get_local_world_size)
66
+ def get_local_world_size(self) -> int:
67
+ return session.get_local_world_size()
68
+
69
+ @_copy_doc(session.get_node_rank)
70
+ def get_node_rank(self) -> int:
71
+ return session.get_node_rank()
72
+
73
+ @DeveloperAPI
74
+ @_copy_doc(session.get_storage)
75
+ def get_storage(self) -> StorageContext:
76
+ return session.get_storage()
77
+
78
+
79
+ @PublicAPI(stability="stable")
80
+ def get_context() -> TrainContext:
81
+ """Get or create a singleton training context.
82
+
83
+ The context is only available in a training or tuning loop.
84
+
85
+ See the :class:`~ray.train.TrainContext` API reference to see available methods.
86
+ """
87
+ global _default_context
88
+
89
+ with _context_lock:
90
+ if _default_context is None:
91
+ _default_context = TrainContext()
92
+ return _default_context
vllm/lib/python3.10/site-packages/ray/train/data_parallel_trainer.py ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import uuid
3
+ from typing import Any, Callable, Dict, List, Optional, Type, Union
4
+
5
+ import ray
6
+ from ray._private.ray_constants import env_integer
7
+ from ray._private.thirdparty.tabulate.tabulate import tabulate
8
+ from ray.air.config import RunConfig, ScalingConfig
9
+ from ray.train import BackendConfig, Checkpoint, TrainingIterator
10
+ from ray.train._internal import session
11
+ from ray.train._internal.backend_executor import BackendExecutor, TrialInfo
12
+ from ray.train._internal.data_config import DataConfig
13
+ from ray.train._internal.session import _TrainingResult, get_session
14
+ from ray.train._internal.utils import construct_train_func, count_required_parameters
15
+ from ray.train.constants import RAY_TRAIN_ENABLE_STATE_TRACKING
16
+ from ray.train.trainer import BaseTrainer, GenDataset
17
+ from ray.util.annotations import DeveloperAPI, PublicAPI
18
+ from ray.widgets import Template
19
+ from ray.widgets.util import repr_with_fallback
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ @DeveloperAPI
25
+ class DataParallelTrainer(BaseTrainer):
26
+ """A Trainer for data parallel training.
27
+
28
+ You should subclass this Trainer if your Trainer follows SPMD (single program,
29
+ multiple data) programming paradigm - you want multiple processes to run the same
30
+ function, but on different data.
31
+
32
+ This Trainer runs the function ``train_loop_per_worker`` on multiple Ray
33
+ Actors.
34
+
35
+ The ``train_loop_per_worker`` function is expected to take in either 0 or 1
36
+ arguments:
37
+
38
+ .. testcode::
39
+
40
+ def train_loop_per_worker():
41
+ ...
42
+
43
+ .. testcode::
44
+
45
+ def train_loop_per_worker(config: Dict):
46
+ ...
47
+
48
+ If ``train_loop_per_worker`` accepts an argument, then
49
+ ``train_loop_config`` will be passed in as the argument. This is useful if you
50
+ want to tune the values in ``train_loop_config`` as hyperparameters.
51
+
52
+ If the ``datasets`` dict contains a training dataset (denoted by
53
+ the "train" key), then it will be split into multiple dataset
54
+ shards that can then be accessed by ``train.get_dataset_shard("train")`` inside
55
+ ``train_loop_per_worker``. All the other datasets will not be split and
56
+ ``train.get_dataset_shard(...)`` will return the the entire Dataset.
57
+
58
+ Inside the ``train_loop_per_worker`` function, you can use any of the
59
+ :ref:`Ray Train loop methods <train-loop-api>`.
60
+
61
+ .. testcode::
62
+
63
+ from ray import train
64
+
65
+ def train_loop_per_worker():
66
+ # Report intermediate results for callbacks or logging and
67
+ # checkpoint data.
68
+ train.report(...)
69
+
70
+ # Returns dict of last saved checkpoint.
71
+ train.get_checkpoint()
72
+
73
+ # Returns the Dataset shard for the given key.
74
+ train.get_dataset_shard("my_dataset")
75
+
76
+ # Returns the total number of workers executing training.
77
+ train.get_context().get_world_size()
78
+
79
+ # Returns the rank of this worker.
80
+ train.get_context().get_world_rank()
81
+
82
+ # Returns the rank of the worker on the current node.
83
+ train.get_context().get_local_rank()
84
+
85
+ Any returns from the ``train_loop_per_worker`` will be discarded and not
86
+ used or persisted anywhere.
87
+
88
+ **How do I use DataParallelTrainer or any of its subclasses?**
89
+
90
+ Example:
91
+
92
+ .. testcode::
93
+
94
+ import ray
95
+ from ray import train
96
+ from ray.train import ScalingConfig
97
+ from ray.train.data_parallel_trainer import DataParallelTrainer
98
+
99
+ def train_loop_for_worker():
100
+ dataset_shard_for_this_worker = train.get_dataset_shard("train")
101
+
102
+ # 3 items for 3 workers, each worker gets 1 item
103
+ batches = list(dataset_shard_for_this_worker.iter_batches(batch_size=1))
104
+ assert len(batches) == 1
105
+
106
+ train_dataset = ray.data.from_items([1, 2, 3])
107
+ assert train_dataset.count() == 3
108
+ trainer = DataParallelTrainer(
109
+ train_loop_for_worker,
110
+ scaling_config=ScalingConfig(num_workers=3),
111
+ datasets={"train": train_dataset},
112
+ )
113
+ result = trainer.fit()
114
+
115
+ .. testoutput::
116
+ :hide:
117
+
118
+ ...
119
+
120
+ **How do I develop on top of DataParallelTrainer?**
121
+
122
+ In many cases, using DataParallelTrainer directly is sufficient to execute
123
+ functions on multiple actors.
124
+
125
+ However, you may want to subclass ``DataParallelTrainer`` and create a custom
126
+ Trainer for the following 2 use cases:
127
+
128
+ - **Use Case 1:** You want to do data parallel training, but want to have
129
+ a predefined ``training_loop_per_worker``.
130
+
131
+ - **Use Case 2:** You want to implement a custom
132
+ :py:class:`~ray.train.backend.Backend` that automatically handles
133
+ additional setup or teardown logic on each actor, so that the users of this
134
+ new trainer do not have to implement this logic. For example, a
135
+ ``TensorflowTrainer`` can be built on top of ``DataParallelTrainer``
136
+ that automatically handles setting the proper environment variables for
137
+ distributed Tensorflow on each actor.
138
+
139
+ For 1, you can set a predefined training loop in __init__
140
+
141
+ .. testcode::
142
+
143
+ from ray.train.data_parallel_trainer import DataParallelTrainer
144
+
145
+ class MyDataParallelTrainer(DataParallelTrainer):
146
+ def __init__(self, *args, **kwargs):
147
+ predefined_train_loop_per_worker = lambda: 1
148
+ super().__init__(predefined_train_loop_per_worker, *args, **kwargs)
149
+
150
+
151
+ For 2, you can implement the ``ray.train.Backend`` and ``ray.train.BackendConfig``
152
+ interfaces.
153
+
154
+ .. testcode::
155
+
156
+ from dataclasses import dataclass
157
+ from ray.train.backend import Backend, BackendConfig
158
+
159
+ class MyBackend(Backend):
160
+ def on_start(self, worker_group, backend_config):
161
+ def set_env_var(env_var_value):
162
+ import os
163
+ os.environ["MY_ENV_VAR"] = env_var_value
164
+
165
+ worker_group.execute(set_env_var, backend_config.env_var)
166
+
167
+ @dataclass
168
+ class MyBackendConfig(BackendConfig):
169
+ env_var: str = "default_value"
170
+
171
+ def backend_cls(self):
172
+ return MyBackend
173
+
174
+ class MyTrainer(DataParallelTrainer):
175
+ def __init__(self, train_loop_per_worker, my_backend_config:
176
+ MyBackendConfig, **kwargs):
177
+
178
+ super().__init__(
179
+ train_loop_per_worker,
180
+ backend_config=my_backend_config, **kwargs)
181
+
182
+ Args:
183
+ train_loop_per_worker: The training function to execute.
184
+ This can either take in no arguments or a ``config`` dict.
185
+ train_loop_config: Configurations to pass into
186
+ ``train_loop_per_worker`` if it accepts an argument.
187
+ backend_config: Configuration for setting up a Backend (e.g. Torch,
188
+ Tensorflow, Horovod) on each worker to enable distributed
189
+ communication. If no Backend should be set up, then set this to None.
190
+ scaling_config: Configuration for how to scale data parallel training.
191
+ dataset_config: Configuration for dataset ingest. This is merged with the
192
+ default dataset config for the given trainer (`cls._dataset_config`).
193
+ run_config: Configuration for the execution of the training run.
194
+ datasets: Ray Datasets to use for training and evaluation.
195
+ This is a dict where the key is the name of the dataset, which
196
+ can be accessed from within the ``train_loop_per_worker`` by calling
197
+ ``train.get_dataset_shard(dataset_key)``.
198
+ By default, all datasets are sharded equally across workers.
199
+ This can be configured via ``dataset_config``.
200
+ metadata: Dict that should be made available via
201
+ `train.get_context().get_metadata()` and in `checkpoint.get_metadata()`
202
+ for checkpoints saved from this Trainer. Must be JSON-serializable.
203
+ resume_from_checkpoint: A checkpoint to resume training from.
204
+ """
205
+
206
+ # Exposed here for testing purposes. Should never need
207
+ # to be overriden.
208
+ _backend_executor_cls: Type[BackendExecutor] = BackendExecutor
209
+ _training_iterator_cls: Type[TrainingIterator] = TrainingIterator
210
+
211
+ _scaling_config_allowed_keys = BaseTrainer._scaling_config_allowed_keys + [
212
+ "num_workers",
213
+ "resources_per_worker",
214
+ "use_gpu",
215
+ "placement_strategy",
216
+ "accelerator_type",
217
+ ]
218
+
219
+ # For backwards compatibility with the legacy dataset config API.
220
+ _dataset_config = None
221
+
222
+ _fields_for_tuner_param_space = BaseTrainer._fields_for_tuner_param_space + [
223
+ "train_loop_config"
224
+ ]
225
+
226
+ def __init__(
227
+ self,
228
+ train_loop_per_worker: Union[Callable[[], None], Callable[[Dict], None]],
229
+ *,
230
+ train_loop_config: Optional[Dict] = None,
231
+ backend_config: Optional[BackendConfig] = None,
232
+ scaling_config: Optional[ScalingConfig] = None,
233
+ dataset_config: Optional[DataConfig] = None,
234
+ run_config: Optional[RunConfig] = None,
235
+ datasets: Optional[Dict[str, GenDataset]] = None,
236
+ metadata: Optional[Dict[str, Any]] = None,
237
+ resume_from_checkpoint: Optional[Checkpoint] = None,
238
+ ):
239
+ self._train_loop_per_worker = train_loop_per_worker
240
+ self._train_loop_config = train_loop_config
241
+
242
+ if dataset_config is None:
243
+ dataset_config = DataConfig()
244
+
245
+ if not isinstance(dataset_config, DataConfig):
246
+ raise ValueError(
247
+ "`dataset_config` must be an instance of ray.train.DataConfig, "
248
+ f"was: {dataset_config}"
249
+ )
250
+ self._data_config = dataset_config
251
+
252
+ backend_config = (
253
+ backend_config if backend_config is not None else BackendConfig()
254
+ )
255
+ self._backend_config = backend_config
256
+
257
+ super(DataParallelTrainer, self).__init__(
258
+ scaling_config=scaling_config,
259
+ run_config=run_config,
260
+ datasets=datasets,
261
+ metadata=metadata,
262
+ resume_from_checkpoint=resume_from_checkpoint,
263
+ )
264
+
265
+ train_total_resources = self.scaling_config.total_resources
266
+ self._data_config.set_train_total_resources(
267
+ train_total_resources.get("CPU", 0),
268
+ train_total_resources.get("GPU", 0),
269
+ )
270
+
271
+ if env_integer(RAY_TRAIN_ENABLE_STATE_TRACKING, 0):
272
+ from ray.train._internal.state.state_actor import get_or_create_state_actor
273
+
274
+ get_or_create_state_actor()
275
+
276
+ @PublicAPI(stability="beta")
277
+ @classmethod
278
+ def restore(
279
+ cls: Type["DataParallelTrainer"],
280
+ path: str,
281
+ train_loop_per_worker: Optional[
282
+ Union[Callable[[], None], Callable[[Dict], None]]
283
+ ] = None,
284
+ train_loop_config: Optional[Dict] = None,
285
+ **kwargs,
286
+ ) -> "DataParallelTrainer":
287
+ """Restores a DataParallelTrainer from a previously interrupted/failed run.
288
+
289
+ Args:
290
+ train_loop_per_worker: Optionally re-specified train loop function.
291
+ This should be used to re-specify a function that is not
292
+ restorable in a new Ray cluster (e.g., it holds onto outdated
293
+ object references). This should be the same training loop
294
+ that was passed to the original trainer constructor.
295
+ train_loop_config: Optionally re-specified train config.
296
+ This should similarly be used if the original `train_loop_config`
297
+ contained outdated object references, and it should not be modified
298
+ from what was originally passed in.
299
+
300
+ See :meth:`BaseTrainer.restore() <ray.train.trainer.BaseTrainer.restore>`
301
+ for descriptions of the other arguments.
302
+
303
+ Returns:
304
+ DataParallelTrainer: A restored instance of the `DataParallelTrainer`
305
+ subclass that is calling this method.
306
+ """
307
+ return super(DataParallelTrainer, cls).restore(
308
+ path=path,
309
+ train_loop_per_worker=train_loop_per_worker,
310
+ train_loop_config=train_loop_config,
311
+ **kwargs,
312
+ )
313
+
314
+ def _validate_attributes(self):
315
+ super()._validate_attributes()
316
+
317
+ self._validate_train_loop_per_worker(
318
+ self._train_loop_per_worker, "train_loop_per_worker"
319
+ )
320
+
321
+ def _validate_train_loop_per_worker(
322
+ self, train_loop_per_worker: Callable, fn_name: str
323
+ ) -> None:
324
+ num_required_params = count_required_parameters(train_loop_per_worker)
325
+ if num_required_params > 1:
326
+ raise ValueError(
327
+ f"{fn_name} should take in 0 or 1 arguments, "
328
+ f"but it accepts {num_required_params} arguments instead."
329
+ )
330
+
331
+ @classmethod
332
+ def _validate_scaling_config(cls, scaling_config: ScalingConfig) -> ScalingConfig:
333
+ scaling_config = super(DataParallelTrainer, cls)._validate_scaling_config(
334
+ scaling_config
335
+ )
336
+
337
+ # This validation happens after the scaling config is updated from
338
+ # its specification in the Tuner `param_space`
339
+ if not scaling_config.use_gpu and "GPU" in ray.available_resources():
340
+ logger.info(
341
+ "GPUs are detected in your Ray cluster, but GPU "
342
+ "training is not enabled for this trainer. To enable "
343
+ "GPU training, make sure to set `use_gpu` to True "
344
+ "in your scaling config."
345
+ )
346
+
347
+ if scaling_config.num_workers is None:
348
+ raise ValueError(
349
+ "You must specify the 'num_workers' in `scaling_config` as either an "
350
+ f"argument of `{cls.__name__}` or through the `param_space` of a "
351
+ "`Tuner` (if performing hyperparameter tuning)."
352
+ )
353
+
354
+ if scaling_config.num_workers <= 0:
355
+ raise ValueError(
356
+ "'num_workers' in `scaling_config` must be a positive "
357
+ f"integer. Received {scaling_config.num_workers}"
358
+ )
359
+
360
+ return scaling_config
361
+
362
+ def _run_training(self, training_iterator: TrainingIterator) -> None:
363
+ """This method loops over the `TrainingIterator`:
364
+ The actual iteration (for ... in ...) waits for the training function
365
+ on each worker to report a result and supplies it as a list of results.
366
+ Afterwards (in the body of the loop), it will report the result
367
+ to the Tune session.
368
+ The iterator ends after the training function on each worker has finished.
369
+ """
370
+ for training_results in training_iterator:
371
+ # TODO(ml-team): add ability to report results from multiple workers.
372
+ self._propagate_results(training_results)
373
+
374
+ def _propagate_results(self, training_results: List[_TrainingResult]):
375
+ first_worker_result = training_results[0]
376
+ assert all(isinstance(result, _TrainingResult) for result in training_results)
377
+
378
+ tune_session = get_session()
379
+
380
+ # Check if any workers reported a checkpoint.
381
+ # If so, report a checkpoint pointing to the persisted location
382
+ # to Tune for book-keeping.
383
+ # NOTE: This removes the restriction for any individual worker
384
+ # (ex: global rank 0 worker) from needing to report a checkpoint.
385
+ # All workers reported a checkpoint to the same fs path, so there's
386
+ # no need to report multiple checkpoints to Tune.
387
+ worker_checkpoints = [
388
+ result.checkpoint
389
+ for result in training_results
390
+ if result.checkpoint is not None
391
+ ]
392
+ at_least_one_reported_checkpoint = len(worker_checkpoints) > 0
393
+
394
+ if at_least_one_reported_checkpoint:
395
+ # Update the coordinator's checkpoint index to the latest.
396
+ # This is what keeps the checkpoint index in line with the workers.
397
+ tune_session.storage._update_checkpoint_index(first_worker_result.metrics)
398
+
399
+ # Make sure that all workers uploaded to the same location.
400
+ assert all(
401
+ checkpoint.path == tune_session.storage.checkpoint_fs_path
402
+ for checkpoint in worker_checkpoints
403
+ )
404
+
405
+ checkpoint = (
406
+ Checkpoint(
407
+ filesystem=tune_session.storage.storage_filesystem,
408
+ path=tune_session.storage.checkpoint_fs_path,
409
+ )
410
+ if at_least_one_reported_checkpoint
411
+ else None
412
+ )
413
+
414
+ tracked_training_result = _TrainingResult(
415
+ checkpoint=checkpoint,
416
+ metrics=first_worker_result.metrics,
417
+ )
418
+
419
+ logger.debug(
420
+ "Report (metrics, checkpoint) to the Tune session:\n"
421
+ f" metrics={tracked_training_result.metrics}\n"
422
+ f" checkpoint={tracked_training_result.checkpoint}"
423
+ )
424
+
425
+ # Report the metrics and checkpoint to Tune.
426
+ tune_session._report_training_result(tracked_training_result)
427
+
428
+ def training_loop(self) -> None:
429
+ scaling_config = self._validate_scaling_config(self.scaling_config)
430
+
431
+ train_loop_per_worker = construct_train_func(
432
+ self._train_loop_per_worker,
433
+ self._train_loop_config,
434
+ train_func_context=self._backend_config.train_func_context,
435
+ fn_arg_name="train_loop_per_worker",
436
+ discard_returns=True,
437
+ )
438
+
439
+ trial_info = TrialInfo(
440
+ name=session.get_trial_name(),
441
+ id=session.get_trial_id(),
442
+ resources=session.get_trial_resources(),
443
+ logdir=session.get_trial_dir(),
444
+ driver_ip=ray.util.get_node_ip_address(),
445
+ driver_node_id=ray.get_runtime_context().get_node_id(),
446
+ experiment_name=session.get_experiment_name(),
447
+ run_id=uuid.uuid4().hex,
448
+ )
449
+
450
+ backend_executor = self._backend_executor_cls(
451
+ backend_config=self._backend_config,
452
+ trial_info=trial_info,
453
+ num_workers=scaling_config.num_workers,
454
+ resources_per_worker=scaling_config._resources_per_worker_not_none,
455
+ max_retries=0,
456
+ )
457
+
458
+ # Start the remote actors.
459
+ backend_executor.start()
460
+
461
+ training_iterator = self._training_iterator_cls(
462
+ backend_executor=backend_executor,
463
+ backend_config=self._backend_config,
464
+ train_func=train_loop_per_worker,
465
+ datasets=self.datasets,
466
+ metadata=self.metadata,
467
+ data_config=self._data_config,
468
+ checkpoint=self.starting_checkpoint,
469
+ )
470
+
471
+ self._run_training(training_iterator)
472
+
473
+ # Shutdown workers.
474
+ backend_executor.shutdown()
475
+
476
+ def get_dataset_config(self) -> DataConfig:
477
+ """Returns a copy of this Trainer's final dataset configs.
478
+
479
+ Returns:
480
+ The merged default + user-supplied dataset config.
481
+ """
482
+
483
+ return self._data_config
484
+
485
+ @repr_with_fallback(["ipywidgets", "8"])
486
+ def _repr_mimebundle_(self, **kwargs):
487
+ """Returns a mimebundle with an ipywidget repr and a simple text repr.
488
+
489
+ Depending on the frontend where the data is being displayed,
490
+ different mimetypes will be used from this bundle.
491
+ See https://ipython.readthedocs.io/en/stable/config/integrating.html
492
+ for information about this method, and
493
+ https://ipywidgets.readthedocs.io/en/latest/embedding.html
494
+ for more information about the jupyter widget mimetype.
495
+
496
+ Returns:
497
+ A mimebundle containing an ipywidget repr and a simple text repr.
498
+ """
499
+ from ipywidgets import HTML, Layout, Tab, VBox
500
+
501
+ title = HTML(f"<h2>{self.__class__.__name__}</h2>")
502
+
503
+ children = []
504
+ titles = []
505
+
506
+ if self.datasets:
507
+ children.append(self._datasets_repr_())
508
+ titles.append("Datasets")
509
+
510
+ children.append(HTML(self._data_config_repr_html_()))
511
+ titles.append("Data Config")
512
+
513
+ if self._train_loop_config:
514
+ children.append(HTML(self._train_loop_config_repr_html_()))
515
+ titles.append("Train Loop Config")
516
+
517
+ if self.scaling_config:
518
+ children.append(HTML(self.scaling_config._repr_html_()))
519
+ titles.append("Scaling Config")
520
+
521
+ if self.run_config:
522
+ children.append(HTML(self.run_config._repr_html_()))
523
+ titles.append("Run Config")
524
+
525
+ if self._backend_config:
526
+ children.append(HTML(self._backend_config._repr_html_()))
527
+ titles.append("Backend Config")
528
+
529
+ tab = Tab(children, titles=titles)
530
+ widget = VBox([title, tab], layout=Layout(width="100%"))
531
+ bundle = widget._repr_mimebundle_(**kwargs)
532
+ bundle.update(
533
+ {
534
+ "text/plain": repr(self),
535
+ }
536
+ )
537
+ return bundle
538
+
539
+ def _train_loop_config_repr_html_(self) -> str:
540
+ if self._train_loop_config:
541
+ table_data = {}
542
+ for k, v in self._train_loop_config.items():
543
+ if isinstance(v, str) or str(v).isnumeric():
544
+ table_data[k] = v
545
+ elif hasattr(v, "_repr_html_"):
546
+ table_data[k] = v._repr_html_()
547
+ else:
548
+ table_data[k] = str(v)
549
+
550
+ return Template("title_data.html.j2").render(
551
+ title="Train Loop Config",
552
+ data=Template("scrollableTable.html.j2").render(
553
+ table=tabulate(
554
+ table_data.items(),
555
+ headers=["Setting", "Value"],
556
+ showindex=False,
557
+ tablefmt="unsafehtml",
558
+ ),
559
+ max_height="none",
560
+ ),
561
+ )
562
+ else:
563
+ return ""
564
+
565
+ def _data_config_repr_html_(self) -> str:
566
+ # TODO make this rendering nicer.
567
+ content = [str(self._data_config)]
568
+ return Template("rendered_html_common.html.j2").render(content=content)
569
+
570
+ def _datasets_repr_(self) -> str:
571
+ from ipywidgets import HTML, Layout, VBox
572
+
573
+ content = []
574
+ if self.datasets:
575
+ for name, config in self.datasets.items():
576
+ tab = config._tab_repr_()
577
+ if tab:
578
+ content.append(
579
+ HTML(
580
+ Template("title_data.html.j2").render(
581
+ title=f"Dataset - <code>{name}</code>", data=None
582
+ )
583
+ )
584
+ )
585
+ content.append(config._tab_repr_())
586
+
587
+ return VBox(content, layout=Layout(width="100%"))
vllm/lib/python3.10/site-packages/ray/train/error.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from ray.util.annotations import PublicAPI
2
+
3
+
4
+ @PublicAPI(stability="beta")
5
+ class SessionMisuseError(Exception):
6
+ """Indicates a method or function was used outside of a session."""
vllm/lib/python3.10/site-packages/ray/train/examples/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/ray/train/examples/horovod/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/ray/train/examples/horovod/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (176 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/train/examples/horovod/__pycache__/horovod_cifar_pbt_example.cpython-310.pyc ADDED
Binary file (4.64 kB). View file
 
vllm/lib/python3.10/site-packages/ray/train/examples/horovod/__pycache__/horovod_example.cpython-310.pyc ADDED
Binary file (6.51 kB). View file
 
vllm/lib/python3.10/site-packages/ray/train/examples/horovod/__pycache__/horovod_pytorch_example.cpython-310.pyc ADDED
Binary file (6.22 kB). View file
 
vllm/lib/python3.10/site-packages/ray/train/examples/horovod/__pycache__/horovod_tune_example.cpython-310.pyc ADDED
Binary file (4.11 kB). View file
 
vllm/lib/python3.10/site-packages/ray/train/examples/horovod/horovod_cifar_pbt_example.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import tempfile
3
+
4
+ import numpy as np
5
+ import torch
6
+ import torch.nn as nn
7
+ import torchvision
8
+ import torchvision.transforms as transforms
9
+ from torch.utils.data import DataLoader
10
+ from torchvision.models import resnet18
11
+
12
+ import ray
13
+ import ray.cloudpickle as cpickle
14
+ import ray.train.torch
15
+ from ray import train, tune
16
+ from ray.train import (
17
+ Checkpoint,
18
+ CheckpointConfig,
19
+ FailureConfig,
20
+ RunConfig,
21
+ ScalingConfig,
22
+ )
23
+ from ray.train.horovod import HorovodTrainer
24
+ from ray.tune.schedulers import create_scheduler
25
+ from ray.tune.tune_config import TuneConfig
26
+ from ray.tune.tuner import Tuner
27
+ from ray.tune.utils.release_test_util import ProgressCallback
28
+
29
+ # The long running version starts 4 trials while only 2 can be run at a time.
30
+ # Thus trials are paused and restored at all times so that every trial can make
31
+ # progress. The PBT scheduler also applies perturbation and mutation,
32
+ # which also involves pausing and restoring.
33
+ # The intention is to stress test the pausing and restoring of trials,
34
+ # especially that there should be no GPU memory leak.
35
+
36
+ # TODO(ml-team): This test is very low signal at the moment.
37
+ # We should further trim it down.
38
+
39
+ CIFAR10_STATS = {
40
+ "mean": (0.4914, 0.4822, 0.4465),
41
+ "std": (0.2023, 0.1994, 0.2010),
42
+ }
43
+
44
+
45
+ def train_loop_per_worker(config):
46
+ import horovod.torch as hvd
47
+
48
+ hvd.init()
49
+ device = ray.train.torch.get_device()
50
+ net = resnet18().to(device)
51
+ optimizer = torch.optim.SGD(
52
+ net.parameters(),
53
+ lr=config["lr"],
54
+ )
55
+ epoch = 0
56
+
57
+ checkpoint = train.get_checkpoint()
58
+ if checkpoint:
59
+ with checkpoint.as_directory() as checkpoint_dir:
60
+ with open(os.path.join(checkpoint_dir, "data.ckpt"), "rb") as fp:
61
+ checkpoint_dict = cpickle.load(fp)
62
+
63
+ model_state = checkpoint_dict["model_state"]
64
+ optimizer_state = checkpoint_dict["optimizer_state"]
65
+ epoch = checkpoint_dict["epoch"] + 1
66
+
67
+ net.load_state_dict(model_state)
68
+ optimizer.load_state_dict(optimizer_state)
69
+
70
+ criterion = nn.CrossEntropyLoss()
71
+ optimizer = hvd.DistributedOptimizer(optimizer)
72
+ np.random.seed(1 + hvd.rank())
73
+ torch.manual_seed(1234)
74
+ # To ensure consistent initialization across workers,
75
+ hvd.broadcast_parameters(net.state_dict(), root_rank=0)
76
+ hvd.broadcast_optimizer_state(optimizer, root_rank=0)
77
+
78
+ trainset = ray.get(config["data"])
79
+
80
+ train_sampler = torch.utils.data.distributed.DistributedSampler(
81
+ trainset, num_replicas=hvd.size(), rank=hvd.rank()
82
+ )
83
+
84
+ # Note, don't set `num_workers` in DataLoader (not even 1),
85
+ # as that will separately start multiple processes (each corresponding to 1 worker)
86
+ # to load the data. This is known to cause issues with Ray.
87
+ trainloader = DataLoader(
88
+ trainset, batch_size=int(config["batch_size"]), sampler=train_sampler
89
+ )
90
+
91
+ for current_epoch in range(epoch, 40): # loop over the dataset multiple times
92
+ running_loss = 0.0
93
+ epoch_steps = 0
94
+ for i, data in enumerate(trainloader):
95
+ # get the inputs; data is a list of [inputs, labels]
96
+ inputs, labels = data
97
+ inputs, labels = inputs.to(device), labels.to(device)
98
+
99
+ # zero the parameter gradients
100
+ optimizer.zero_grad()
101
+
102
+ # forward + backward + optimize
103
+ outputs = net(inputs)
104
+ loss = criterion(outputs, labels)
105
+ loss.backward()
106
+ optimizer.step()
107
+
108
+ # print statistics
109
+ running_loss += loss.item()
110
+ epoch_steps += 1
111
+
112
+ if i % 2000 == 1999: # print every 2000 mini-batches
113
+ print(
114
+ "[%d, %5d] loss: %.3f"
115
+ % (current_epoch + 1, i + 1, running_loss / epoch_steps)
116
+ )
117
+
118
+ if config["smoke_test"]:
119
+ break
120
+
121
+ with tempfile.TemporaryDirectory() as checkpoint_dir:
122
+ with open(os.path.join(checkpoint_dir, "data.ckpt"), "wb") as fp:
123
+ cpickle.dump(
124
+ dict(
125
+ model_state=net.state_dict(),
126
+ optimizer_state=optimizer.state_dict(),
127
+ epoch=current_epoch,
128
+ ),
129
+ fp,
130
+ )
131
+ checkpoint = Checkpoint.from_directory(checkpoint_dir)
132
+ train.report(dict(loss=running_loss / epoch_steps), checkpoint=checkpoint)
133
+
134
+
135
+ if __name__ == "__main__":
136
+ import argparse
137
+
138
+ parser = argparse.ArgumentParser()
139
+ parser.add_argument(
140
+ "--smoke-test", action="store_true", help=("Finish quickly for testing.")
141
+ )
142
+ args = parser.parse_args()
143
+
144
+ if args.smoke_test:
145
+ ray.init()
146
+ else:
147
+ ray.init(address="auto") # assumes ray is started with ray up
148
+
149
+ transform_train = transforms.Compose(
150
+ [
151
+ transforms.RandomCrop(32, padding=4),
152
+ transforms.RandomHorizontalFlip(),
153
+ transforms.ToTensor(),
154
+ transforms.Normalize(CIFAR10_STATS["mean"], CIFAR10_STATS["std"]),
155
+ ]
156
+ ) # meanstd transformation
157
+
158
+ dataset = torchvision.datasets.CIFAR10(
159
+ root="/tmp/data_cifar", train=True, download=True, transform=transform_train
160
+ )
161
+
162
+ horovod_trainer = HorovodTrainer(
163
+ train_loop_per_worker=train_loop_per_worker,
164
+ scaling_config=ScalingConfig(
165
+ use_gpu=False if args.smoke_test else True,
166
+ num_workers=2,
167
+ ),
168
+ train_loop_config={"batch_size": 64, "data": ray.put(dataset)},
169
+ )
170
+
171
+ # ensure that checkpointing works.
172
+ pbt = create_scheduler(
173
+ "pbt",
174
+ perturbation_interval=1, # To make perturb more often.
175
+ hyperparam_mutations={
176
+ "train_loop_config": {"lr": tune.uniform(0.001, 0.1)},
177
+ },
178
+ )
179
+
180
+ tuner = Tuner(
181
+ horovod_trainer,
182
+ param_space={
183
+ "train_loop_config": {
184
+ "lr": 0.1
185
+ if args.smoke_test
186
+ else tune.grid_search([0.1 * i for i in range(1, 5)]), # 4 trials
187
+ "smoke_test": args.smoke_test,
188
+ }
189
+ },
190
+ tune_config=TuneConfig(
191
+ num_samples=2 if args.smoke_test else 1,
192
+ metric="loss",
193
+ mode="min",
194
+ scheduler=pbt,
195
+ ),
196
+ run_config=RunConfig(
197
+ stop={"training_iteration": 1} if args.smoke_test else None,
198
+ failure_config=FailureConfig(fail_fast=False),
199
+ checkpoint_config=CheckpointConfig(num_to_keep=1),
200
+ callbacks=[ProgressCallback()],
201
+ ),
202
+ )
203
+
204
+ result_grid = tuner.fit()
205
+
206
+ # Make sure trials do not fail.
207
+ for result in result_grid:
208
+ assert not result.error
209
+
210
+ print("Best hyperparameters found were: ", result_grid.get_best_result().config)
vllm/lib/python3.10/site-packages/ray/train/examples/horovod/horovod_example.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+
4
+ import horovod.torch as hvd
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ import torch.optim as optim
8
+ import torch.utils.data.distributed
9
+ from filelock import FileLock
10
+ from torchvision import datasets, transforms
11
+
12
+ import ray
13
+ from ray import train
14
+ from ray.train import ScalingConfig
15
+ from ray.train.horovod import HorovodTrainer
16
+
17
+
18
+ def metric_average(val, name):
19
+ tensor = torch.tensor(val)
20
+ avg_tensor = hvd.allreduce(tensor, name=name)
21
+ return avg_tensor.item()
22
+
23
+
24
+ class Net(nn.Module):
25
+ def __init__(self):
26
+ super(Net, self).__init__()
27
+ self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
28
+ self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
29
+ self.conv2_drop = nn.Dropout2d()
30
+ self.fc1 = nn.Linear(320, 50)
31
+ self.fc2 = nn.Linear(50, 10)
32
+
33
+ def forward(self, x):
34
+ x = F.relu(F.max_pool2d(self.conv1(x), 2))
35
+ x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
36
+ x = x.view(-1, 320)
37
+ x = F.relu(self.fc1(x))
38
+ x = F.dropout(x, training=self.training)
39
+ x = self.fc2(x)
40
+ return F.log_softmax(x)
41
+
42
+
43
+ def setup(config):
44
+ data_dir = config.get("data_dir", None)
45
+ seed = config.get("seed", 42)
46
+ batch_size = config.get("batch_size", 64)
47
+ use_adasum = config.get("use_adasum", False)
48
+ lr = config.get("lr", 0.01)
49
+ momentum = config.get("momentum", 0.5)
50
+ use_cuda = config.get("use_cuda", False)
51
+
52
+ # Horovod: initialize library.
53
+ hvd.init()
54
+ torch.manual_seed(seed)
55
+
56
+ if use_cuda:
57
+ # Horovod: pin GPU to local rank.
58
+ torch.cuda.set_device(hvd.local_rank())
59
+ torch.cuda.manual_seed(seed)
60
+
61
+ # Horovod: limit # of CPU threads to be used per worker.
62
+ torch.set_num_threads(1)
63
+
64
+ kwargs = {"num_workers": 1, "pin_memory": True} if use_cuda else {}
65
+ data_dir = data_dir or "~/data"
66
+ with FileLock(os.path.expanduser("~/.horovod_lock")):
67
+ train_dataset = datasets.MNIST(
68
+ data_dir,
69
+ train=True,
70
+ download=True,
71
+ transform=transforms.Compose(
72
+ [transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]
73
+ ),
74
+ )
75
+ # Horovod: use DistributedSampler to partition the training data.
76
+ train_sampler = torch.utils.data.distributed.DistributedSampler(
77
+ train_dataset, num_replicas=hvd.size(), rank=hvd.rank()
78
+ )
79
+ train_loader = torch.utils.data.DataLoader(
80
+ train_dataset, batch_size=batch_size, sampler=train_sampler, **kwargs
81
+ )
82
+
83
+ model = Net()
84
+
85
+ # By default, Adasum doesn't need scaling up learning rate.
86
+ lr_scaler = hvd.size() if not use_adasum else 1
87
+
88
+ if use_cuda:
89
+ # Move model to GPU.
90
+ model.cuda()
91
+ # If using GPU Adasum allreduce, scale learning rate by local_size.
92
+ if use_adasum and hvd.nccl_built():
93
+ lr_scaler = hvd.local_size()
94
+
95
+ # Horovod: scale learning rate by lr_scaler.
96
+ optimizer = optim.SGD(model.parameters(), lr=lr * lr_scaler, momentum=momentum)
97
+
98
+ # Horovod: wrap optimizer with DistributedOptimizer.
99
+ optimizer = hvd.DistributedOptimizer(
100
+ optimizer,
101
+ named_parameters=model.named_parameters(),
102
+ op=hvd.Adasum if use_adasum else hvd.Average,
103
+ )
104
+
105
+ return model, optimizer, train_loader, train_sampler
106
+
107
+
108
+ def train_epoch(
109
+ model, optimizer, train_sampler, train_loader, epoch, log_interval, use_cuda
110
+ ):
111
+ loss = None
112
+ model.train()
113
+ # Horovod: set epoch to sampler for shuffling.
114
+ train_sampler.set_epoch(epoch)
115
+ for batch_idx, (data, target) in enumerate(train_loader):
116
+ if use_cuda:
117
+ data, target = data.cuda(), target.cuda()
118
+ optimizer.zero_grad()
119
+ output = model(data)
120
+ loss = F.nll_loss(output, target)
121
+ loss.backward()
122
+ optimizer.step()
123
+ if batch_idx % log_interval == 0:
124
+ # Horovod: use train_sampler to determine the number of
125
+ # examples in this worker's partition.
126
+ print(
127
+ "Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}".format(
128
+ epoch,
129
+ batch_idx * len(data),
130
+ len(train_sampler),
131
+ 100.0 * batch_idx / len(train_loader),
132
+ loss.item(),
133
+ )
134
+ )
135
+ return loss.item() if loss else None
136
+
137
+
138
+ # Horovod function API.
139
+
140
+
141
+ def train_func(config):
142
+ num_epochs = config.get("num_epochs", 10)
143
+ log_interval = config.get("log_interval", 10)
144
+ use_cuda = config.get("use_cuda", False)
145
+
146
+ model, optimizer, train_loader, train_sampler = setup(config)
147
+
148
+ for epoch in range(num_epochs):
149
+ loss = train_epoch(
150
+ model, optimizer, train_sampler, train_loader, epoch, log_interval, use_cuda
151
+ )
152
+ train.report(dict(loss=loss))
153
+
154
+
155
+ def main(num_workers, use_gpu, kwargs):
156
+ trainer = HorovodTrainer(
157
+ train_func,
158
+ train_loop_config=kwargs,
159
+ scaling_config=ScalingConfig(use_gpu=use_gpu, num_workers=num_workers),
160
+ )
161
+ results = trainer.fit()
162
+ print(results.metrics)
163
+
164
+
165
+ # Horovod Class API.
166
+
167
+
168
+ class HorovodTrainClass:
169
+ def __init__(self, config):
170
+ self.log_interval = config.get("log_interval", 10)
171
+ self.use_cuda = config.get("use_cuda", False)
172
+
173
+ if self.use_cuda:
174
+ torch.cuda.set_device(hvd.local_rank())
175
+
176
+ self.model, self.optimizer, self.train_loader, self.train_sampler = setup(
177
+ config
178
+ )
179
+
180
+ def train(self, epoch):
181
+ loss = train_epoch(
182
+ self.model,
183
+ self.optimizer,
184
+ self.train_sampler,
185
+ self.train_loader,
186
+ epoch,
187
+ self.log_interval,
188
+ self.use_cuda,
189
+ )
190
+ return loss
191
+
192
+
193
+ if __name__ == "__main__":
194
+ # Training settings
195
+ parser = argparse.ArgumentParser(
196
+ description="PyTorch MNIST Example",
197
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
198
+ )
199
+ parser.add_argument(
200
+ "--batch-size",
201
+ type=int,
202
+ default=64,
203
+ metavar="N",
204
+ help="input batch size for training (default: 64)",
205
+ )
206
+ parser.add_argument(
207
+ "--num-epochs",
208
+ type=int,
209
+ default=5,
210
+ metavar="N",
211
+ help="number of epochs to train (default: 10)",
212
+ )
213
+ parser.add_argument(
214
+ "--lr",
215
+ type=float,
216
+ default=0.01,
217
+ metavar="LR",
218
+ help="learning rate (default: 0.01)",
219
+ )
220
+ parser.add_argument(
221
+ "--momentum",
222
+ type=float,
223
+ default=0.5,
224
+ metavar="M",
225
+ help="SGD momentum (default: 0.5)",
226
+ )
227
+ parser.add_argument(
228
+ "--use-gpu", action="store_true", default=False, help="enables CUDA training"
229
+ )
230
+ parser.add_argument(
231
+ "--seed", type=int, default=42, metavar="S", help="random seed (default: 42)"
232
+ )
233
+ parser.add_argument(
234
+ "--log-interval",
235
+ type=int,
236
+ default=10,
237
+ metavar="N",
238
+ help="how many batches to wait before logging training status",
239
+ )
240
+ parser.add_argument(
241
+ "--use-adasum",
242
+ action="store_true",
243
+ default=False,
244
+ help="use adasum algorithm to do reduction",
245
+ )
246
+ parser.add_argument(
247
+ "--num-workers",
248
+ type=int,
249
+ default=2,
250
+ help="Number of Ray workers to use for training.",
251
+ )
252
+ parser.add_argument(
253
+ "--data-dir",
254
+ help="location of the training dataset in the local filesystem ("
255
+ "will be downloaded if needed)",
256
+ )
257
+ parser.add_argument(
258
+ "--address",
259
+ required=False,
260
+ type=str,
261
+ default=None,
262
+ help="Address of Ray cluster.",
263
+ )
264
+
265
+ args = parser.parse_args()
266
+
267
+ if args.address:
268
+ ray.init(args.address)
269
+ else:
270
+ ray.init()
271
+
272
+ use_cuda = args.use_gpu if args.use_gpu is not None else False
273
+
274
+ kwargs = {
275
+ "data_dir": args.data_dir,
276
+ "seed": args.seed,
277
+ "use_cuda": use_cuda,
278
+ "batch_size": args.batch_size,
279
+ "use_adasum": args.use_adasum if args.use_adasum else False,
280
+ "lr": args.lr,
281
+ "momentum": args.momentum,
282
+ "num_epochs": args.num_epochs,
283
+ "log_interval": args.log_interval,
284
+ }
285
+
286
+ main(num_workers=args.num_workers, use_gpu=use_cuda, kwargs=kwargs)
vllm/lib/python3.10/site-packages/ray/train/examples/horovod/horovod_pytorch_example.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import tempfile
4
+
5
+ import horovod.torch as hvd
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+ import torch.optim as optim
9
+ import torch.utils.data.distributed
10
+ from filelock import FileLock
11
+ from torchvision import datasets, transforms
12
+
13
+ import ray.train.torch
14
+ from ray import train
15
+ from ray.train import Checkpoint, ScalingConfig
16
+ from ray.train.horovod import HorovodTrainer
17
+
18
+
19
+ def metric_average(val, name):
20
+ tensor = torch.tensor(val)
21
+ avg_tensor = hvd.allreduce(tensor, name=name)
22
+ return avg_tensor.item()
23
+
24
+
25
+ class Net(nn.Module):
26
+ def __init__(self):
27
+ super(Net, self).__init__()
28
+ self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
29
+ self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
30
+ self.conv2_drop = nn.Dropout2d()
31
+ self.fc1 = nn.Linear(320, 50)
32
+ self.fc2 = nn.Linear(50, 10)
33
+
34
+ def forward(self, x):
35
+ x = F.relu(F.max_pool2d(self.conv1(x), 2))
36
+ x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
37
+ x = x.view(-1, 320)
38
+ x = F.relu(self.fc1(x))
39
+ x = F.dropout(x, training=self.training)
40
+ x = self.fc2(x)
41
+ return F.log_softmax(x)
42
+
43
+
44
+ def setup(config):
45
+ data_dir = config.get("data_dir", None)
46
+ seed = config.get("seed", 42)
47
+ batch_size = config.get("batch_size", 64)
48
+ use_adasum = config.get("use_adasum", False)
49
+ lr = config.get("lr", 0.01)
50
+ momentum = config.get("momentum", 0.5)
51
+ use_cuda = config.get("use_cuda", False)
52
+
53
+ # Horovod: initialize library.
54
+ hvd.init()
55
+ torch.manual_seed(seed)
56
+
57
+ if use_cuda:
58
+ # Horovod: pin GPU to local rank.
59
+ torch.cuda.set_device(hvd.local_rank())
60
+ torch.cuda.manual_seed(seed)
61
+
62
+ # Horovod: limit # of CPU threads to be used per worker.
63
+ torch.set_num_threads(1)
64
+
65
+ kwargs = {"pin_memory": True} if use_cuda else {}
66
+ data_dir = data_dir or "~/data"
67
+ with FileLock(os.path.expanduser("~/.horovod_lock")):
68
+ train_dataset = datasets.MNIST(
69
+ data_dir,
70
+ train=True,
71
+ download=True,
72
+ transform=transforms.Compose(
73
+ [transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]
74
+ ),
75
+ )
76
+ # Horovod: use DistributedSampler to partition the training data.
77
+ train_sampler = torch.utils.data.distributed.DistributedSampler(
78
+ train_dataset, num_replicas=hvd.size(), rank=hvd.rank()
79
+ )
80
+ # Note, don't set `num_workers` in DataLoader (not even 1),
81
+ # as that will separately start multiple processes (each corresponding to 1 worker)
82
+ # to load the data. This is known to cause issues with Ray.
83
+ train_loader = torch.utils.data.DataLoader(
84
+ train_dataset, batch_size=batch_size, sampler=train_sampler, **kwargs
85
+ )
86
+
87
+ model = Net()
88
+
89
+ # By default, Adasum doesn't need scaling up learning rate.
90
+ lr_scaler = hvd.size() if not use_adasum else 1
91
+
92
+ if use_cuda:
93
+ # Move model to GPU.
94
+ model.cuda()
95
+ # If using GPU Adasum allreduce, scale learning rate by local_size.
96
+ if use_adasum and hvd.nccl_built():
97
+ lr_scaler = hvd.local_size()
98
+
99
+ # Horovod: scale learning rate by lr_scaler.
100
+ optimizer = optim.SGD(model.parameters(), lr=lr * lr_scaler, momentum=momentum)
101
+
102
+ # Horovod: wrap optimizer with DistributedOptimizer.
103
+ optimizer = hvd.DistributedOptimizer(
104
+ optimizer,
105
+ named_parameters=model.named_parameters(),
106
+ op=hvd.Adasum if use_adasum else hvd.Average,
107
+ )
108
+
109
+ return model, optimizer, train_loader, train_sampler
110
+
111
+
112
+ def train_epoch(
113
+ model, optimizer, train_sampler, train_loader, epoch, log_interval, use_cuda
114
+ ):
115
+ loss = None
116
+ model.train()
117
+ # Horovod: set epoch to sampler for shuffling.
118
+ train_sampler.set_epoch(epoch)
119
+ for batch_idx, (data, target) in enumerate(train_loader):
120
+ if use_cuda:
121
+ data, target = data.cuda(), target.cuda()
122
+ optimizer.zero_grad()
123
+ output = model(data)
124
+ loss = F.nll_loss(output, target)
125
+ loss.backward()
126
+ optimizer.step()
127
+ if batch_idx % log_interval == 0:
128
+ # Horovod: use train_sampler to determine the number of
129
+ # examples in this worker's partition.
130
+ print(
131
+ "Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}".format(
132
+ epoch,
133
+ batch_idx * len(data),
134
+ len(train_sampler),
135
+ 100.0 * batch_idx / len(train_loader),
136
+ loss.item(),
137
+ )
138
+ )
139
+ return loss.item() if loss else None
140
+
141
+
142
+ def train_func(config):
143
+ num_epochs = config.get("num_epochs", 10)
144
+ log_interval = config.get("log_interval", 10)
145
+ use_cuda = config.get("use_cuda", False)
146
+
147
+ model, optimizer, train_loader, train_sampler = setup(config)
148
+
149
+ results = []
150
+ for epoch in range(num_epochs):
151
+ loss = train_epoch(
152
+ model, optimizer, train_sampler, train_loader, epoch, log_interval, use_cuda
153
+ )
154
+ results.append(loss)
155
+ with tempfile.TemporaryDirectory() as tmpdir:
156
+ torch.save(model.state_dict(), os.path.join(tmpdir, "model.pt"))
157
+ train.report({"loss": loss}, checkpoint=Checkpoint.from_directory(tmpdir))
158
+
159
+ # Only used for testing.
160
+ return results
161
+
162
+
163
+ def main(num_workers, use_gpu, kwargs):
164
+ trainer = HorovodTrainer(
165
+ train_loop_per_worker=train_func,
166
+ train_loop_config={
167
+ "num_epochs": kwargs["num_epochs"],
168
+ "log_interval": kwargs["log_interval"],
169
+ "use_cuda": kwargs["use_cuda"],
170
+ },
171
+ scaling_config=ScalingConfig(num_workers=num_workers, use_gpu=use_gpu),
172
+ )
173
+ result = trainer.fit()
174
+ print(result)
175
+
176
+
177
+ if __name__ == "__main__":
178
+ # Training settings
179
+ parser = argparse.ArgumentParser(
180
+ description="PyTorch MNIST Example",
181
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
182
+ )
183
+ parser.add_argument(
184
+ "--batch-size",
185
+ type=int,
186
+ default=64,
187
+ metavar="N",
188
+ help="input batch size for training (default: 64)",
189
+ )
190
+ parser.add_argument(
191
+ "--num-epochs",
192
+ type=int,
193
+ default=5,
194
+ metavar="N",
195
+ help="number of epochs to train (default: 10)",
196
+ )
197
+ parser.add_argument(
198
+ "--lr",
199
+ type=float,
200
+ default=0.01,
201
+ metavar="LR",
202
+ help="learning rate (default: 0.01)",
203
+ )
204
+ parser.add_argument(
205
+ "--momentum",
206
+ type=float,
207
+ default=0.5,
208
+ metavar="M",
209
+ help="SGD momentum (default: 0.5)",
210
+ )
211
+ parser.add_argument(
212
+ "--use-gpu", action="store_true", default=False, help="enables CUDA training"
213
+ )
214
+ parser.add_argument(
215
+ "--seed", type=int, default=42, metavar="S", help="random seed (default: 42)"
216
+ )
217
+ parser.add_argument(
218
+ "--log-interval",
219
+ type=int,
220
+ default=10,
221
+ metavar="N",
222
+ help="how many batches to wait before logging training status",
223
+ )
224
+ parser.add_argument(
225
+ "--use-adasum",
226
+ action="store_true",
227
+ default=False,
228
+ help="use adasum algorithm to do reduction",
229
+ )
230
+ parser.add_argument(
231
+ "--num-workers",
232
+ type=int,
233
+ default=2,
234
+ help="Number of Ray workers to use for training.",
235
+ )
236
+ parser.add_argument(
237
+ "--data-dir",
238
+ help="location of the training dataset in the local filesystem ("
239
+ "will be downloaded if needed)",
240
+ )
241
+ parser.add_argument(
242
+ "--address",
243
+ required=False,
244
+ type=str,
245
+ default=None,
246
+ help="Address of Ray cluster.",
247
+ )
248
+
249
+ args = parser.parse_args()
250
+
251
+ if args.address:
252
+ ray.init(args.address)
253
+ else:
254
+ ray.init()
255
+
256
+ use_cuda = args.use_gpu if args.use_gpu is not None else False
257
+
258
+ kwargs = {
259
+ "data_dir": args.data_dir,
260
+ "seed": args.seed,
261
+ "use_cuda": use_cuda,
262
+ "batch_size": args.batch_size,
263
+ "use_adasum": args.use_adasum if args.use_adasum else False,
264
+ "lr": args.lr,
265
+ "momentum": args.momentum,
266
+ "num_epochs": args.num_epochs,
267
+ "log_interval": args.log_interval,
268
+ }
269
+
270
+ main(num_workers=args.num_workers, use_gpu=use_cuda, kwargs=kwargs)