TheHassanSaud commited on
Commit
e9ee478
·
1 Parent(s): e43d144

Upload folder using huggingface_hub (part 30)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +21 -0
  2. pace_revision_2/.venv-pace/lib/python3.11/site-packages/torchgen/packaged/autograd/templates/variable_factories.h +135 -0
  3. pace_revision_2/.venv-pace/lib/python3.11/site-packages/torchgen/selective_build/__init__.py +0 -0
  4. pace_revision_2/.venv-pace/lib/python3.11/site-packages/torchgen/selective_build/operator.py +171 -0
  5. pace_revision_2/.venv-pace/lib/python3.11/site-packages/torchgen/selective_build/selector.py +352 -0
  6. pace_revision_2/.venv-pace/lib/python3.11/site-packages/torchgen/static_runtime/__init__.py +0 -0
  7. pace_revision_2/.venv-pace/lib/python3.11/site-packages/torchgen/static_runtime/config.py +388 -0
  8. pace_revision_2/.venv-pace/lib/python3.11/site-packages/torchgen/static_runtime/gen_static_runtime_ops.py +231 -0
  9. pace_revision_2/.venv-pace/lib/python3.11/site-packages/torchgen/static_runtime/generator.py +814 -0
  10. pace_revision_2/.venv-pace/lib/python3.11/site-packages/torchgen/utils.py +568 -0
  11. pace_revision_2/.venv-pace/lib/python3.11/site-packages/torchgen/yaml_utils.py +26 -0
  12. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm-4.70.1.dist-info/METADATA +1600 -0
  13. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm-4.70.1.dist-info/RECORD +40 -0
  14. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm-4.70.1.dist-info/WHEEL +5 -0
  15. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm-4.70.1.dist-info/entry_points.txt +2 -0
  16. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm-4.70.1.dist-info/licenses/LICENCE +49 -0
  17. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm-4.70.1.dist-info/top_level.txt +1 -0
  18. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/__init__.py +38 -0
  19. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/__main__.py +3 -0
  20. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/__pycache__/__init__.cpython-311.pyc +0 -0
  21. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/__pycache__/_monitor.cpython-311.pyc +0 -0
  22. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/__pycache__/_tqdm_pandas.cpython-311.pyc +0 -0
  23. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/__pycache__/cli.cpython-311.pyc +0 -0
  24. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/__pycache__/gui.cpython-311.pyc +0 -0
  25. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/__pycache__/std.cpython-311.pyc +0 -0
  26. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/__pycache__/utils.cpython-311.pyc +0 -0
  27. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/__pycache__/version.cpython-311.pyc +0 -0
  28. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/_main.py +9 -0
  29. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/_monitor.py +104 -0
  30. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/_tqdm.py +9 -0
  31. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/_tqdm_gui.py +9 -0
  32. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/_tqdm_notebook.py +9 -0
  33. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/_tqdm_pandas.py +24 -0
  34. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/_utils.py +11 -0
  35. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/asyncio.py +103 -0
  36. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/auto.py +40 -0
  37. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/autonotebook.py +38 -0
  38. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/cli.py +324 -0
  39. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/completion.sh +19 -0
  40. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/contrib/__init__.py +91 -0
  41. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/contrib/bells.py +28 -0
  42. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/contrib/concurrent.py +259 -0
  43. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/contrib/discord.py +155 -0
  44. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/contrib/itertools.py +92 -0
  45. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/contrib/logging.py +128 -0
  46. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/contrib/slack.py +119 -0
  47. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/contrib/telegram.py +152 -0
  48. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/contrib/utils_worker.py +38 -0
  49. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/dask.py +44 -0
  50. pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/gui.py +179 -0
.gitattributes CHANGED
@@ -1298,3 +1298,24 @@ pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/onnx/_internal/tor
1298
  pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/onnx/_internal/torchscript_exporter/__pycache__/symbolic_opset9.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
1299
  pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/optim/__pycache__/lr_scheduler.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
1300
  pace_revision_2/.venv-pace/lib/python3.11/site-packages/torchgen/__pycache__/model.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1298
  pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/onnx/_internal/torchscript_exporter/__pycache__/symbolic_opset9.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
1299
  pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/optim/__pycache__/lr_scheduler.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
1300
  pace_revision_2/.venv-pace/lib/python3.11/site-packages/torchgen/__pycache__/model.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
1301
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/triton/FileCheck filter=lfs diff=lfs merge=lfs -text
1302
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/triton/_C/libproton.so filter=lfs diff=lfs merge=lfs -text
1303
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/triton/_C/libtriton.so filter=lfs diff=lfs merge=lfs -text
1304
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/triton/backends/amd/lib/ockl.bc filter=lfs diff=lfs merge=lfs -text
1305
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/triton/backends/amd/lib/ocml.bc filter=lfs diff=lfs merge=lfs -text
1306
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/bin/cuobjdump filter=lfs diff=lfs merge=lfs -text
1307
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/bin/nvdisasm filter=lfs diff=lfs merge=lfs -text
1308
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/bin/ptxas filter=lfs diff=lfs merge=lfs -text
1309
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/lib/cupti/libcheckpoint.so filter=lfs diff=lfs merge=lfs -text
1310
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/lib/cupti/libcupti.so filter=lfs diff=lfs merge=lfs -text
1311
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/lib/cupti/libcupti.so.12 filter=lfs diff=lfs merge=lfs -text
1312
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/lib/cupti/libcupti.so.2025.1.1 filter=lfs diff=lfs merge=lfs -text
1313
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/lib/cupti/libcupti_static.a filter=lfs diff=lfs merge=lfs -text
1314
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/lib/cupti/libnvperf_host.so filter=lfs diff=lfs merge=lfs -text
1315
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/lib/cupti/libnvperf_host_static.a filter=lfs diff=lfs merge=lfs -text
1316
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/lib/cupti/libnvperf_target.so filter=lfs diff=lfs merge=lfs -text
1317
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/lib/cupti/libpcsamplingutil.so filter=lfs diff=lfs merge=lfs -text
1318
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/lib/libdevice.10.bc filter=lfs diff=lfs merge=lfs -text
1319
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/triton/instrumentation/libGPUInstrumentationTestLib.so filter=lfs diff=lfs merge=lfs -text
1320
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/triton/instrumentation/libPrintLoadStoreMemSpaces.so filter=lfs diff=lfs merge=lfs -text
1321
+ pace_revision_2/.venv-pace/lib/python3.11/site-packages/triton/language/__pycache__/core.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torchgen/packaged/autograd/templates/variable_factories.h ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // ${generated_comment}
4
+
5
+ #include <ATen/core/Tensor.h>
6
+ #include <ATen/TracerMode.h>
7
+ #include <ATen/core/grad_mode.h>
8
+ #include <c10/util/ArrayRef.h>
9
+ #include <c10/core/MemoryFormat.h>
10
+ #include <torch/csrc/api/include/torch/detail/TensorDataContainer.h>
11
+ #include <torch/csrc/autograd/variable.h>
12
+
13
+ #ifndef AT_PER_OPERATOR_HEADERS
14
+ #include <ATen/Functions.h>
15
+ #else
16
+ #include <ATen/ops/from_blob.h>
17
+ $ops_headers
18
+ #endif
19
+
20
+ #include <functional>
21
+ #include <initializer_list>
22
+ #include <utility>
23
+
24
+ namespace torch {
25
+
26
+ /// NOTE: Currently `torch::tensor(...)` doesn't support mixed data types
27
+ /// (i.e. `torch::tensor({{bool, 2.0}})` doesn't work). We might be able to
28
+ /// support it in the future by iterating over all sub-lists to find
29
+ /// the largest data type that can represent all of the elements, or by using
30
+ /// variadic templates.
31
+ ///
32
+ /// NOTE: C++ `torch::tensor` with a floating-point type or an `at::ArrayRef` / `std::vector` /
33
+ /// (nested) braced-init-list of floating-point types always produces a tensor of dtype
34
+ /// `torch::get_default_dtype()`, matching Python `torch.tensor` behavior.
35
+ ///
36
+ /// NOTE: C++ `torch::tensor` with an integer type or an `at::ArrayRef` / `std::vector` /
37
+ /// (nested) braced-init-list of integer types always produces a tensor of dtype `at::kLong`
38
+ /// (aka. int64_t), matching Python `torch.tensor` behavior.
39
+ ///
40
+ /// NOTE: The following dtypes are not supported by `torch::tensor` currently:
41
+ /// - `unsigned int`
42
+ /// - `unsigned long int`
43
+ /// - `unsigned long long int`
44
+ /// - `long long int`
45
+ inline at::Tensor tensor(detail::TensorDataContainer tensor_data_container, const at::TensorOptions& options = {}) {
46
+ return autograd::make_variable(
47
+ // note: we remove the requires_grad setting from the TensorOptions because
48
+ // it is ignored anyways (and we actually have an assertion that it isn't set
49
+ // which would fail otherwise). We handle requires_grad explicitly here
50
+ // instead of passing it through to the kernel.
51
+ tensor_data_container.convert_to_tensor(options.requires_grad(::std::nullopt)),
52
+ options.requires_grad());
53
+ }
54
+
55
+ /// A generic deleter function.
56
+ using Deleter = std::function<void(void*)>;
57
+ using at::MemoryFormat;
58
+
59
+ /// Exposes the given `data` as a `Tensor` without taking ownership of the
60
+ /// original data. `sizes` should specify the shape of the tensor, `strides` the
61
+ /// stride in each dimension. The `deleter` function (a
62
+ /// `std::function<void(void*)>`) will be called on the `data` when the Tensor
63
+ /// data would normally be deallocated. The `TensorOptions` specify additional
64
+ /// configuration options for the returned tensor, such as what type to
65
+ /// interpret the `data` as.
66
+ inline at::Tensor from_blob(
67
+ void* data,
68
+ at::IntArrayRef sizes,
69
+ at::IntArrayRef strides,
70
+ const Deleter& deleter,
71
+ const at::TensorOptions& options = at::TensorOptions()) {
72
+ at::Tensor tensor = ([&]() {
73
+ at::AutoDispatchBelowAutograd guard; // TODO: remove
74
+ at::tracer::impl::NoTracerDispatchMode tracer_guard;
75
+ return at::from_blob(data, sizes, strides, deleter, options.requires_grad(::std::nullopt));
76
+ })();
77
+ return autograd::make_variable(tensor, options.requires_grad());
78
+ }
79
+
80
+ /// Exposes the given `data` as a `Tensor` without taking ownership of the
81
+ /// original data. `sizes` should specify the shape of the tensor, `strides` the
82
+ /// stride in each dimension. The `TensorOptions`
83
+ /// specify additional configuration options for the returned tensor, such as
84
+ /// what type to interpret the `data` as.
85
+ inline at::Tensor from_blob(
86
+ void* data,
87
+ at::IntArrayRef sizes,
88
+ at::IntArrayRef strides,
89
+ const at::TensorOptions& options = at::TensorOptions()) {
90
+ at::Tensor tensor = ([&]() {
91
+ at::AutoDispatchBelowAutograd guard; // TODO: remove
92
+ at::tracer::impl::NoTracerDispatchMode tracer_guard;
93
+ return at::from_blob(data, sizes, strides, options.requires_grad(::std::nullopt));
94
+ })();
95
+ return autograd::make_variable(tensor, options.requires_grad());
96
+ }
97
+
98
+ /// Exposes the given `data` as a `Tensor` without taking ownership of the
99
+ /// original data. `sizes` should specify the shape of the tensor. The `deleter`
100
+ /// (a `std::function<void(void*)>`) function will be called on the `data` when
101
+ /// the Tensor data would normally be deallocated. The `TensorOptions` specify
102
+ /// additional configuration options for the returned tensor, such as what type
103
+ /// to interpret the `data` as.
104
+ inline at::Tensor from_blob(
105
+ void* data,
106
+ at::IntArrayRef sizes,
107
+ const Deleter& deleter,
108
+ const at::TensorOptions& options = at::TensorOptions()) {
109
+ at::Tensor tensor = ([&]() {
110
+ at::AutoDispatchBelowAutograd guard; // TODO: remove
111
+ at::tracer::impl::NoTracerDispatchMode tracer_guard;
112
+ return at::from_blob(data, sizes, deleter, options.requires_grad(::std::nullopt));
113
+ })();
114
+ return autograd::make_variable(tensor, options.requires_grad());
115
+ }
116
+
117
+ /// Exposes the given `data` as a `Tensor` without taking ownership of the
118
+ /// original data. `sizes` should specify the shape of the tensor. The
119
+ /// `TensorOptions` specify additional configuration options for the returned
120
+ /// tensor, such as what type to interpret the `data` as.
121
+ inline at::Tensor from_blob(
122
+ void* data,
123
+ at::IntArrayRef sizes,
124
+ const at::TensorOptions& options = at::TensorOptions()) {
125
+ at::Tensor tensor = ([&]() {
126
+ at::AutoDispatchBelowAutograd guard; // TODO: remove
127
+ at::tracer::impl::NoTracerDispatchMode tracer_guard;
128
+ return at::from_blob(data, sizes, options.requires_grad(::std::nullopt));
129
+ })();
130
+ return autograd::make_variable(tensor, options.requires_grad());
131
+ }
132
+
133
+ ${function_definitions}
134
+
135
+ } // namespace torch
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torchgen/selective_build/__init__.py ADDED
File without changes
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torchgen/selective_build/operator.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+
5
+
6
+ # This class holds information about a single operator used to determine
7
+ # the outcome of a selective/custom PyTorch build that doesn't include
8
+ # registration code for all the supported operators. This is done to
9
+ # reduce the size of the generated binary so that it can be deployed in
10
+ # situations where binary size comes at a premium.
11
+ #
12
+ @dataclass(frozen=True)
13
+ class SelectiveBuildOperator:
14
+ # The name of the operator. This includes the aten::, etc... prefix
15
+ # The operator name may or may not have the overload name. If this
16
+ # operator name does not specify an overload name, the way to determine
17
+ # if this entry refers to the family of operators with this base name
18
+ # or just the operator with this name is to look at the value of the
19
+ # 'include_all_overloads' flag in this class.
20
+ name: str
21
+
22
+ # True if this is a root operator (i.e. called directly from a
23
+ # TorchScript model, etc...). An operator is considered to be a
24
+ # root operator if it is called directly from any one of the models
25
+ # that this instance of the pytorch library was built for. Hence, it
26
+ # may not be a root operator in all of the models that are used in
27
+ # this instance of the pytorch library.
28
+ is_root_operator: bool
29
+
30
+ # Is this operator used for on-device training? If True, then we need to
31
+ # use the information to generate code in VariableType_N.cpp for registration
32
+ # of training related operators. Again, this is True if this operator
33
+ # is used for training in one or more models used by this instance of the
34
+ # pytorch library.
35
+ is_used_for_training: bool
36
+
37
+ # If True, it indicates that this operator instance (object) refers to an
38
+ # operator without the overload name and should apply to all overloads
39
+ # which have this operator name as the base name. This flag is applicable
40
+ # only for objects that have operator names without a DOT (period) character
41
+ # in them.
42
+ #
43
+ # Note: This flag is a temporary workaround to grandfather in the current
44
+ # static selective (custom) build mechanism, which largely ignores overload
45
+ # names when determining whether to select operators for registration
46
+ # purposes.
47
+ include_all_overloads: bool
48
+
49
+ # Debug Information at the operator level
50
+ _debug_info: tuple[str, ...] | None
51
+
52
+ @staticmethod
53
+ def from_yaml_dict(
54
+ op_name: str, op_info: dict[str, object]
55
+ ) -> SelectiveBuildOperator:
56
+ allowed_keys = {
57
+ "name",
58
+ "is_root_operator",
59
+ "is_used_for_training",
60
+ "include_all_overloads",
61
+ "debug_info",
62
+ }
63
+
64
+ if len(set(op_info.keys()) - allowed_keys) > 0:
65
+ raise Exception( # noqa: TRY002
66
+ "Got unexpected top level keys: {}".format(
67
+ ",".join(set(op_info.keys()) - allowed_keys),
68
+ )
69
+ )
70
+
71
+ if "name" in op_info:
72
+ assert op_name == op_info["name"]
73
+
74
+ is_root_operator = op_info.get("is_root_operator", True)
75
+ assert isinstance(is_root_operator, bool)
76
+
77
+ is_used_for_training = op_info.get("is_used_for_training", True)
78
+ assert isinstance(is_used_for_training, bool)
79
+
80
+ include_all_overloads = op_info.get("include_all_overloads", True)
81
+ assert isinstance(include_all_overloads, bool)
82
+
83
+ debug_info: tuple[str, ...] | None = None
84
+ if "debug_info" in op_info:
85
+ di_list = op_info["debug_info"]
86
+ assert isinstance(di_list, list)
87
+ debug_info = tuple(str(x) for x in di_list)
88
+
89
+ return SelectiveBuildOperator(
90
+ name=op_name,
91
+ is_root_operator=is_root_operator,
92
+ is_used_for_training=is_used_for_training,
93
+ include_all_overloads=include_all_overloads,
94
+ _debug_info=debug_info,
95
+ )
96
+
97
+ @staticmethod
98
+ def from_legacy_operator_name_without_overload(
99
+ name: str,
100
+ ) -> SelectiveBuildOperator:
101
+ return SelectiveBuildOperator(
102
+ name=name,
103
+ is_root_operator=True,
104
+ is_used_for_training=True,
105
+ include_all_overloads=True,
106
+ _debug_info=None,
107
+ )
108
+
109
+ def to_dict(self) -> dict[str, object]:
110
+ ret: dict[str, object] = {
111
+ "is_root_operator": self.is_root_operator,
112
+ "is_used_for_training": self.is_used_for_training,
113
+ "include_all_overloads": self.include_all_overloads,
114
+ }
115
+ if self._debug_info is not None:
116
+ ret["debug_info"] = self._debug_info
117
+
118
+ return ret
119
+
120
+
121
+ def merge_debug_info(
122
+ lhs: tuple[str, ...] | None,
123
+ rhs: tuple[str, ...] | None,
124
+ ) -> tuple[str, ...] | None:
125
+ # Ensure that when merging, each entry shows up just once.
126
+ if lhs is None and rhs is None:
127
+ return None
128
+
129
+ return tuple(set((lhs or ()) + (rhs or ())))
130
+
131
+
132
+ def combine_operators(
133
+ lhs: SelectiveBuildOperator, rhs: SelectiveBuildOperator
134
+ ) -> SelectiveBuildOperator:
135
+ if str(lhs.name) != str(rhs.name):
136
+ raise Exception( # noqa: TRY002
137
+ f"Expected both arguments to have the same name, but got '{str(lhs.name)}' and '{str(rhs.name)}' instead"
138
+ )
139
+
140
+ return SelectiveBuildOperator(
141
+ name=lhs.name,
142
+ # Consider this operator to be a root operator if it is a
143
+ # root operator in any of the models used in this instance of
144
+ # the pytorch library.
145
+ is_root_operator=lhs.is_root_operator or rhs.is_root_operator,
146
+ # Consider this operator to be a training operator if it is
147
+ # an operator used for training in any of the models used
148
+ # in this instance of the pytorch library.
149
+ is_used_for_training=lhs.is_used_for_training or rhs.is_used_for_training,
150
+ include_all_overloads=lhs.include_all_overloads or rhs.include_all_overloads,
151
+ _debug_info=merge_debug_info(lhs._debug_info, rhs._debug_info),
152
+ )
153
+
154
+
155
+ def merge_operator_dicts(
156
+ lhs: dict[str, SelectiveBuildOperator],
157
+ rhs: dict[str, SelectiveBuildOperator],
158
+ ) -> dict[str, SelectiveBuildOperator]:
159
+ operators: dict[str, SelectiveBuildOperator] = {}
160
+ for op_name, op in list(lhs.items()) + list(rhs.items()):
161
+ new_op = op
162
+ if op_name in operators:
163
+ new_op = combine_operators(operators[op_name], op)
164
+
165
+ operators[op_name] = new_op
166
+
167
+ return operators
168
+
169
+
170
+ def strip_operator_overload_name(op_name: str) -> str:
171
+ return op_name.split(".", maxsplit=1)[0]
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torchgen/selective_build/selector.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections import defaultdict
4
+ from collections.abc import Iterable
5
+ from dataclasses import dataclass
6
+ from typing import TYPE_CHECKING
7
+
8
+ import yaml
9
+
10
+ from torchgen.selective_build.operator import (
11
+ merge_debug_info,
12
+ merge_operator_dicts,
13
+ SelectiveBuildOperator,
14
+ strip_operator_overload_name,
15
+ )
16
+
17
+
18
+ if TYPE_CHECKING:
19
+ from torchgen.model import NativeFunction
20
+
21
+
22
+ # A SelectiveBuilder holds information extracted from the selective build
23
+ # YAML specification.
24
+ #
25
+ # It includes information about the build's selectivity, the debug_info
26
+ # associated with this selective build (opaque string), and the set of
27
+ # operators that should be included in the build.
28
+ #
29
+ @dataclass(frozen=True)
30
+ class SelectiveBuilder:
31
+ # If true, then the build is not selective, and includes all
32
+ # operators.
33
+ include_all_operators: bool
34
+
35
+ # Debug Information at the selective/custom build level.
36
+ _debug_info: tuple[str, ...] | None
37
+
38
+ # A dictionary of operator -> operator metadata.
39
+ operators: dict[str, SelectiveBuildOperator]
40
+
41
+ # A dictionary of selected kernel tags and dtypes. Typically a
42
+ # PyTorch Operator Kernel (function) may have many code paths
43
+ # that are specialized for many many Tensor dtypes, so it's not
44
+ # one per kernel function, but there could be many per kernel
45
+ # function. The tag isn't a kernel function name, but some fragment
46
+ # of the kernel function implementation itself.
47
+ kernel_metadata: dict[str, list[str]]
48
+
49
+ # ExecuTorch only. A dictionary of kernel tag -> list of (list of input
50
+ # dtypes for tensor-like input args).
51
+ # This is from selective.yaml
52
+ et_kernel_metadata: dict[str, list[str]]
53
+
54
+ # A set of all the custom torch bind classes used by the selected models
55
+ # Stored as a set internally to remove duplicates proactively, but written
56
+ # as a list to yamls
57
+ custom_classes: set[str]
58
+
59
+ # A set of all the build features used by the selected models
60
+ # Stored as a set internally to remove duplicates proactively, but written
61
+ # as a list to yamls
62
+ build_features: set[str]
63
+
64
+ # If true, then fragments for all dtypes for all kernel functions
65
+ # are included as well as all custom classes. This is typically set when any one of the
66
+ # operator lists is generated from a mechanism other than
67
+ # tracing based selective build.
68
+ include_all_non_op_selectives: bool
69
+
70
+ @staticmethod
71
+ def get_nop_selector() -> SelectiveBuilder:
72
+ return SelectiveBuilder.from_yaml_dict({"include_all_operators": True})
73
+
74
+ @staticmethod
75
+ def from_yaml_dict(data: dict[str, object]) -> SelectiveBuilder:
76
+ valid_top_level_keys = {
77
+ "include_all_non_op_selectives",
78
+ "include_all_operators",
79
+ "debug_info",
80
+ "operators",
81
+ "kernel_metadata",
82
+ "et_kernel_metadata",
83
+ "custom_classes",
84
+ "build_features",
85
+ }
86
+ top_level_keys = set(data.keys())
87
+ if len(top_level_keys - valid_top_level_keys) > 0:
88
+ raise Exception( # noqa: TRY002
89
+ "Got unexpected top level keys: {}".format(
90
+ ",".join(top_level_keys - valid_top_level_keys),
91
+ )
92
+ )
93
+ include_all_operators = data.get("include_all_operators", False)
94
+ assert isinstance(include_all_operators, bool)
95
+
96
+ debug_info = None
97
+ if "debug_info" in data:
98
+ di_list = data["debug_info"]
99
+ assert isinstance(di_list, list)
100
+
101
+ debug_info = tuple(str(x) for x in di_list)
102
+
103
+ operators = {}
104
+ operators_dict = data.get("operators", {})
105
+ assert isinstance(operators_dict, dict)
106
+
107
+ for k, v in operators_dict.items():
108
+ operators[k] = SelectiveBuildOperator.from_yaml_dict(k, v)
109
+
110
+ kernel_metadata = {}
111
+ kernel_metadata_dict = data.get("kernel_metadata", {})
112
+ assert isinstance(kernel_metadata_dict, dict)
113
+
114
+ for k, v in kernel_metadata_dict.items():
115
+ kernel_metadata[str(k)] = [str(dtype) for dtype in v]
116
+
117
+ et_kernel_metadata = data.get("et_kernel_metadata", {})
118
+ assert isinstance(et_kernel_metadata, dict)
119
+
120
+ custom_classes = data.get("custom_classes", [])
121
+ assert isinstance(custom_classes, Iterable)
122
+ custom_classes = set(custom_classes)
123
+
124
+ build_features = data.get("build_features", [])
125
+ assert isinstance(build_features, Iterable)
126
+ build_features = set(build_features)
127
+
128
+ include_all_non_op_selectives = data.get("include_all_non_op_selectives", False)
129
+ assert isinstance(include_all_non_op_selectives, bool)
130
+
131
+ return SelectiveBuilder(
132
+ include_all_operators,
133
+ debug_info,
134
+ operators,
135
+ kernel_metadata,
136
+ et_kernel_metadata,
137
+ custom_classes, # type: ignore[arg-type]
138
+ build_features, # type: ignore[arg-type]
139
+ include_all_non_op_selectives,
140
+ )
141
+
142
+ @staticmethod
143
+ def from_yaml_str(config_contents: str) -> SelectiveBuilder:
144
+ contents = yaml.safe_load(config_contents)
145
+ return SelectiveBuilder.from_yaml_dict(contents)
146
+
147
+ @staticmethod
148
+ def from_yaml_path(config_path: str) -> SelectiveBuilder:
149
+ with open(config_path) as f:
150
+ contents = yaml.safe_load(f)
151
+ return SelectiveBuilder.from_yaml_dict(contents)
152
+
153
+ @staticmethod
154
+ def from_legacy_op_registration_allow_list(
155
+ allow_list: set[str], is_root_operator: bool, is_used_for_training: bool
156
+ ) -> SelectiveBuilder:
157
+ operators = {}
158
+ for op in allow_list:
159
+ operators[op] = {
160
+ "name": op,
161
+ "is_root_operator": is_root_operator,
162
+ "is_used_for_training": is_used_for_training,
163
+ "include_all_overloads": True,
164
+ }
165
+ return SelectiveBuilder.from_yaml_dict(
166
+ {
167
+ "operators": operators,
168
+ "include_all_non_op_selectives": True,
169
+ }
170
+ )
171
+
172
+ def is_operator_selected(self, name: str) -> bool:
173
+ if self.include_all_operators:
174
+ return True
175
+
176
+ if name in self.operators:
177
+ return True
178
+ name = strip_operator_overload_name(name)
179
+ return name in self.operators and self.operators[name].include_all_overloads
180
+
181
+ def is_native_function_selected(self, func: NativeFunction) -> bool:
182
+ op_name = op_name_from_native_function(func)
183
+ return self.is_operator_selected(op_name)
184
+
185
+ def is_operator_selected_for_training(self, name: str) -> bool:
186
+ if not self.is_operator_selected(name):
187
+ return False
188
+ if self.include_all_operators:
189
+ return True
190
+
191
+ not_training_op = SelectiveBuildOperator(
192
+ name="",
193
+ is_root_operator=False,
194
+ is_used_for_training=False,
195
+ include_all_overloads=False,
196
+ _debug_info=None,
197
+ )
198
+ op = not_training_op
199
+ if name in self.operators:
200
+ op = self.operators[name]
201
+
202
+ name = strip_operator_overload_name(name)
203
+ base_op = not_training_op
204
+ if name in self.operators:
205
+ base_op = self.operators[name]
206
+
207
+ return op.is_used_for_training or (
208
+ base_op.include_all_overloads and base_op.is_used_for_training
209
+ )
210
+
211
+ def is_native_function_selected_for_training(self, func: NativeFunction) -> bool:
212
+ op_name = op_name_from_native_function(func)
213
+ return self.is_operator_selected_for_training(op_name)
214
+
215
+ def is_root_operator(self, name: str) -> bool:
216
+ if not self.is_operator_selected(name):
217
+ return False
218
+ if self.include_all_operators:
219
+ return True
220
+
221
+ if name in self.operators:
222
+ op: SelectiveBuildOperator = self.operators[name]
223
+ return op.is_root_operator
224
+ name = strip_operator_overload_name(name)
225
+ if name not in self.operators:
226
+ return False
227
+ base_op: SelectiveBuildOperator = self.operators[name]
228
+ return base_op.include_all_overloads and base_op.is_root_operator
229
+
230
+ def is_kernel_dtype_selected(self, kernel_tag: str, dtype: str) -> bool:
231
+ if self.include_all_operators or self.include_all_non_op_selectives:
232
+ return True
233
+
234
+ return (
235
+ kernel_tag in self.kernel_metadata
236
+ and dtype in self.kernel_metadata[kernel_tag]
237
+ )
238
+
239
+ def et_get_selected_kernels(self, op_name: str, kernel_key: list[str]) -> list[str]:
240
+ """
241
+ Return a list of kernel keys that cover the used ops
242
+ """
243
+ # If no kernel metadata, either it's implied by include_all_operators=True or the op is not used.
244
+ if op_name not in self.et_kernel_metadata:
245
+ return kernel_key if self.include_all_operators else []
246
+ # Otherwise, only return the specific kernel keys.
247
+
248
+ result_set = set()
249
+
250
+ for model_kernel_keys in self.et_kernel_metadata[op_name]:
251
+ key_found = False
252
+ for key in kernel_key:
253
+ # Don't compare the version for now
254
+ if (
255
+ key != "default"
256
+ and key.split("/")[1] == model_kernel_keys.split("/")[1]
257
+ ):
258
+ result_set.add(key)
259
+ key_found = True
260
+ break
261
+ if not key_found:
262
+ if "default" not in kernel_key:
263
+ raise Exception("Missing kernel for the model") # noqa: TRY002
264
+ else:
265
+ result_set.add("default")
266
+
267
+ return list(result_set)
268
+
269
+ def to_dict(self) -> dict[str, object]:
270
+ ret: dict[str, object] = {
271
+ "include_all_non_op_selectives": self.include_all_non_op_selectives,
272
+ "include_all_operators": self.include_all_operators,
273
+ }
274
+ operators = {}
275
+ for op_name, op in self.operators.items():
276
+ operators[op_name] = op.to_dict()
277
+ ret["operators"] = operators
278
+
279
+ if self._debug_info is not None:
280
+ ret["debug_info"] = sorted(self._debug_info)
281
+
282
+ ret["kernel_metadata"] = {
283
+ k: sorted(v) for (k, v) in self.kernel_metadata.items()
284
+ }
285
+
286
+ ret["et_kernel_metadata"] = self.et_kernel_metadata
287
+
288
+ ret["custom_classes"] = sorted(self.custom_classes)
289
+
290
+ ret["build_features"] = sorted(self.build_features)
291
+
292
+ return ret
293
+
294
+
295
+ def merge_kernel_metadata(
296
+ lhs: dict[str, list[str]],
297
+ rhs: dict[str, list[str]],
298
+ ) -> dict[str, list[str]]:
299
+ kernel_metadata: dict[str, list[str]] = {}
300
+ for tag_name, dtypes in list(lhs.items()) + list(rhs.items()):
301
+ dtypes_copy = set(dtypes)
302
+ if tag_name in kernel_metadata:
303
+ dtypes_copy |= set(kernel_metadata[tag_name])
304
+
305
+ kernel_metadata[tag_name] = list(dtypes_copy)
306
+
307
+ return kernel_metadata
308
+
309
+
310
+ def merge_et_kernel_metadata(
311
+ lhs: dict[str, list[str]],
312
+ rhs: dict[str, list[str]],
313
+ ) -> dict[str, list[str]]:
314
+ merge_et_kernel_metadata: dict[str, set[str]] = defaultdict(set)
315
+ for op in list(lhs.keys()) + list(rhs.keys()):
316
+ merge_et_kernel_metadata[op].update(lhs.get(op, []))
317
+ merge_et_kernel_metadata[op].update(rhs.get(op, []))
318
+
319
+ return {op: sorted(val) for op, val in merge_et_kernel_metadata.items()}
320
+
321
+
322
+ def combine_selective_builders(
323
+ lhs: SelectiveBuilder, rhs: SelectiveBuilder
324
+ ) -> SelectiveBuilder:
325
+ include_all_operators = lhs.include_all_operators or rhs.include_all_operators
326
+ debug_info = merge_debug_info(lhs._debug_info, rhs._debug_info)
327
+ operators = merge_operator_dicts(lhs.operators, rhs.operators)
328
+ kernel_metadata = merge_kernel_metadata(lhs.kernel_metadata, rhs.kernel_metadata)
329
+ et_kernel_metadata = merge_et_kernel_metadata(
330
+ lhs.et_kernel_metadata, rhs.et_kernel_metadata
331
+ )
332
+ include_all_non_op_selectives = (
333
+ lhs.include_all_non_op_selectives or rhs.include_all_non_op_selectives
334
+ )
335
+ custom_classes = lhs.custom_classes.union(rhs.custom_classes)
336
+ build_features = lhs.build_features.union(rhs.build_features)
337
+ return SelectiveBuilder(
338
+ include_all_operators,
339
+ debug_info,
340
+ operators,
341
+ kernel_metadata,
342
+ et_kernel_metadata,
343
+ custom_classes,
344
+ build_features,
345
+ include_all_non_op_selectives,
346
+ )
347
+
348
+
349
+ def op_name_from_native_function(f: NativeFunction) -> str:
350
+ # This was originally read from the 'operator_name_with_overload' field in the
351
+ # declaration dict, which was the part before the first '(' in 'schema_string'.
352
+ return f"{f.namespace}::{f.func.name}"
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torchgen/static_runtime/__init__.py ADDED
File without changes
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torchgen/static_runtime/config.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from torchgen.model import NativeFunctionsGroup, NativeFunctionsViewGroup
4
+
5
+
6
+ def func_name_base_str(g: NativeFunctionsGroup | NativeFunctionsViewGroup) -> str:
7
+ if isinstance(g, NativeFunctionsGroup):
8
+ return str(g.functional.func.name.name.base)
9
+ else:
10
+ return str(g.view.root_name)
11
+
12
+
13
+ is_hand_written_ops_ = frozenset(
14
+ (
15
+ "abs",
16
+ "add",
17
+ "addmm",
18
+ "all",
19
+ "any",
20
+ "argmin",
21
+ "bmm",
22
+ "clamp",
23
+ "clamp_min",
24
+ "cumsum",
25
+ "div",
26
+ "fmod",
27
+ "index_select",
28
+ "leaky_relu",
29
+ "linear",
30
+ "log",
31
+ "matmul",
32
+ "mul",
33
+ "narrow_copy",
34
+ "nonzero",
35
+ "pow",
36
+ "remainder",
37
+ "sigmoid",
38
+ "sign",
39
+ "sub",
40
+ "tanh",
41
+ "detach",
42
+ "expand_as",
43
+ "flatten",
44
+ "narrow",
45
+ "reshape_as",
46
+ "select",
47
+ "slice",
48
+ "softmax",
49
+ "split",
50
+ "squeeze",
51
+ "transpose",
52
+ "view",
53
+ "where",
54
+ )
55
+ )
56
+
57
+
58
+ def is_hand_written(g: NativeFunctionsGroup | NativeFunctionsViewGroup) -> bool:
59
+ name_base = func_name_base_str(g)
60
+ return name_base in is_hand_written_ops_
61
+
62
+
63
+ def override_test_values(arg_map: dict[str, str], op_name: str, index: int) -> None:
64
+ assert index == 0 or index == 1
65
+ if op_name == "addr":
66
+ if index == 0:
67
+ arg_map["self"] = "at::rand({6, 6})"
68
+ arg_map["vec1"] = "at::rand({6})"
69
+ arg_map["vec2"] = "at::rand({6})"
70
+ else:
71
+ arg_map["self"] = "at::rand({22, 22})"
72
+ arg_map["vec1"] = "at::rand({22})"
73
+ arg_map["vec2"] = "at::rand({22})"
74
+ return
75
+ if op_name == "mv":
76
+ if index == 0:
77
+ arg_map["self"] = "at::rand({6, 6})"
78
+ arg_map["vec"] = "at::rand({6})"
79
+ else:
80
+ arg_map["self"] = "at::rand({22, 22})"
81
+ arg_map["vec"] = "at::rand({22})"
82
+ return
83
+ if op_name == "addbmm":
84
+ if index == 0:
85
+ arg_map["self"] = "at::rand({6, 6})"
86
+ else:
87
+ arg_map["self"] = "at::rand({22, 22})"
88
+ return
89
+ if op_name == "cross":
90
+ if index == 0:
91
+ arg_map["self"] = "at::rand({3, 3, 3})"
92
+ arg_map["other"] = "at::rand({3, 3, 3})"
93
+ else:
94
+ arg_map["self"] = "at::rand({22, 3, 22})"
95
+ arg_map["other"] = "at::rand({22, 3, 22})"
96
+ return
97
+ if op_name == "take":
98
+ if index == 0:
99
+ arg_map["index"] = "at::randint(0, 216, {20}, torch::kInt64)"
100
+ else:
101
+ arg_map["index"] = "at::randint(0, 1000, {100}, torch::kInt64)"
102
+ return
103
+ if op_name == "take_along_dim":
104
+ if index == 0:
105
+ arg_map["indices"] = "at::argsort(self0, 1, true)"
106
+ else:
107
+ arg_map["indices"] = "at::argsort(self1, 1, true)"
108
+ return
109
+ if op_name == "masked_select":
110
+ if index == 0:
111
+ arg_map["mask"] = "at::randn({6, 6, 6}) > 0.5"
112
+ else:
113
+ arg_map["mask"] = "at::rand({22, 22, 22}) > 0.5"
114
+ return
115
+ if op_name == "orgqr":
116
+ if index == 0:
117
+ arg_map["input2"] = "at::rand({6, 6})"
118
+ else:
119
+ arg_map["input2"] = "at::rand({22, 22})"
120
+ return
121
+ if op_name == "ormqr":
122
+ if index == 0:
123
+ arg_map["input2"] = "at::rand({6, 6})"
124
+ else:
125
+ arg_map["input2"] = "at::rand({22, 22})"
126
+ return
127
+ if op_name == "quantile":
128
+ if index == 0:
129
+ arg_map["q"] = "at::rand({6})"
130
+ arg_map["interpolation"] = '"linear"'
131
+ else:
132
+ arg_map["q"] = "at::rand({22})"
133
+ arg_map["interpolation"] = '"linear"'
134
+ return
135
+ if op_name == "nanquantile":
136
+ if index == 0:
137
+ arg_map["q"] = "at::rand({6})"
138
+ arg_map["interpolation"] = '"linear"'
139
+ else:
140
+ arg_map["q"] = "at::rand({22})"
141
+ arg_map["interpolation"] = '"linear"'
142
+ return
143
+ if op_name == "multi_margin_loss":
144
+ if index == 0:
145
+ arg_map["self"] = "at::rand({6, 6})"
146
+ arg_map["target"] = "at::randint(6, {6}, torch::kInt64)"
147
+ arg_map["weight"] = "at::rand({6})"
148
+ else:
149
+ arg_map["self"] = "at::rand({22, 22})"
150
+ arg_map["target"] = "at::randint(22, {22}, torch::kInt64)"
151
+ arg_map["weight"] = "at::rand({22})"
152
+ return
153
+ if op_name == "multilabel_margin_loss":
154
+ if index == 0:
155
+ arg_map["self"] = "at::rand({6, 6})"
156
+ arg_map["target"] = "at::randint(6, {6, 6}, torch::kInt64)"
157
+ else:
158
+ arg_map["self"] = "at::rand({22, 22})"
159
+ arg_map["target"] = "at::randint(22, {22, 22}, torch::kInt64)"
160
+ return
161
+ if op_name == "nll_loss":
162
+ if index == 0:
163
+ arg_map["self"] = "at::rand({6, 6})"
164
+ arg_map["target"] = "at::randint(6, {6}, torch::kInt64)"
165
+ arg_map["weight"] = "at::rand({6})"
166
+ else:
167
+ arg_map["self"] = "at::rand({22, 22})"
168
+ arg_map["target"] = "at::randint(22, {22}, torch::kInt64)"
169
+ arg_map["weight"] = "at::rand({22})"
170
+ return
171
+ if op_name == "nll_loss2d":
172
+ if index == 0:
173
+ arg_map["self"] = "at::rand({6, 6, 6, 6})"
174
+ arg_map["target"] = "at::randint(6, {6, 6, 6}, torch::kInt64)"
175
+ arg_map["weight"] = "at::rand({6})"
176
+ else:
177
+ arg_map["self"] = "at::rand({22, 22, 22, 22})"
178
+ arg_map["target"] = "at::randint(22, {22, 22, 22}, torch::kInt64)"
179
+ arg_map["weight"] = "at::rand({22})"
180
+ return
181
+ if op_name in (
182
+ "fft_fft",
183
+ "fft_ifft",
184
+ "fft_rfft",
185
+ "fft_irfft",
186
+ "fft_hfft",
187
+ "fft_ihfft",
188
+ ):
189
+ arg_map["norm"] = '"forward"'
190
+ return
191
+ if op_name == "linalg_tensorinv":
192
+ if index == 0:
193
+ arg_map["self"] = "at::rand({6, 6, 6, 6})"
194
+ arg_map["ind"] = "2"
195
+ else:
196
+ arg_map["self"] = "at::rand({22, 22, 22, 22})"
197
+ arg_map["ind"] = "2"
198
+ return
199
+ if op_name == "addmv":
200
+ if index == 0:
201
+ arg_map["self"] = "at::rand({2})"
202
+ arg_map["mat"] = "at::rand({2, 2})"
203
+ arg_map["vec"] = "at::rand({2})"
204
+ else:
205
+ arg_map["self"] = "at::rand({35})"
206
+ arg_map["mat"] = "at::rand({35, 35})"
207
+ arg_map["vec"] = "at::rand({35})"
208
+ return
209
+ if op_name == "acosh":
210
+ if index == 0:
211
+ arg_map["self"] = "at::rand({2, 2, 2}) + at::ones({2, 2, 2})"
212
+ else:
213
+ arg_map["self"] = "at::rand({5, 5, 5}) + at::ones({5, 5, 5})"
214
+ return
215
+ if op_name == "adaptive_max_pool2d_backward":
216
+ if index == 0:
217
+ arg_map["grad_output"] = "at::rand({2, 2, 2}, at::kFloat)"
218
+ arg_map["self"] = "at::rand({2, 2, 2}, at::kFloat)"
219
+ arg_map["indices"] = "at::randint(0, 1, {2, 2, 2}, at::kLong)"
220
+ else:
221
+ arg_map["grad_output"] = "at::rand({3, 3, 3}, at::kFloat)"
222
+ arg_map["self"] = "at::rand({3, 3, 3}, at::kFloat)"
223
+ arg_map["indices"] = "at::randint(0, 1, {3, 3, 3}, at::kLong)"
224
+ return
225
+ if op_name == "adaptive_max_pool3d_backward":
226
+ if index == 0:
227
+ arg_map["grad_output"] = "at::rand({2, 2, 2, 2}, at::kFloat)"
228
+ arg_map["self"] = "at::rand({2, 2, 2, 2}, at::kFloat)"
229
+ arg_map["indices"] = "at::randint(0, 1, {2, 2, 2, 2}, at::kLong)"
230
+ else:
231
+ arg_map["grad_output"] = "at::rand({3, 3, 3, 3}, at::kFloat)"
232
+ arg_map["self"] = "at::rand({3, 3, 3, 3}, at::kFloat)"
233
+ arg_map["indices"] = "at::randint(0, 1, {3, 3, 3, 3}, at::kLong)"
234
+ return
235
+ if op_name == "bitwise_left_shift":
236
+ if index == 0:
237
+ arg_map["self"] = "at::randint(1, 1 << 4, {6, 6, 6}, at::kInt)"
238
+ arg_map["other"] = "at::randint(1, 26, {6, 6, 6}, at::kInt)"
239
+ else:
240
+ arg_map["self"] = "at::randint(1, 1 << 4, {22, 22, 22}, at::kInt)"
241
+ arg_map["other"] = "at::randint(1, 26, {22, 22, 22}, at::kInt)"
242
+ return
243
+ if op_name == "bitwise_right_shift":
244
+ if index == 0:
245
+ arg_map["self"] = "at::randint(1 << 21, 1 << 30, {6, 6, 6}, at::kInt)"
246
+ arg_map["other"] = "at::randint(1, 22, {6, 6, 6}, at::kInt)"
247
+ else:
248
+ arg_map["self"] = "at::randint(1 << 21, 1 << 30, {22, 22, 22}, at::kInt)"
249
+ arg_map["other"] = "at::randint(1, 22, {22, 22, 22}, at::kInt)"
250
+ return
251
+ if op_name == "gather":
252
+ if index == 0:
253
+ arg_map["self"] = "at::randint(1, 100, {2,2,2}, at::kInt)"
254
+ arg_map["dim"] = "1"
255
+ arg_map["index"] = "at::randint(0, 1, {2,2,2}, torch::kInt64)"
256
+ arg_map["sparse_grad"] = "false"
257
+ else:
258
+ arg_map["self"] = "at::randint(1, 100, {5,5,5}, at::kInt)"
259
+ arg_map["dim"] = "1"
260
+ arg_map["index"] = "at::randint(0, 4, {5,5,5}, torch::kInt64)"
261
+ arg_map["sparse_grad"] = "false"
262
+ return
263
+ if op_name == "gelu":
264
+ if index == 0:
265
+ arg_map["self"] = "at::rand({6, 6, 6})"
266
+ arg_map["approximate"] = '"tanh"'
267
+ else:
268
+ arg_map["self"] = "at::rand({22, 22, 22})"
269
+ arg_map["approximate"] = '"tanh"'
270
+ return
271
+ if op_name == "gelu_backward":
272
+ if index == 0:
273
+ arg_map["grad_output"] = "at::rand({6, 6, 6})"
274
+ arg_map["self"] = "at::rand({6, 6, 6})"
275
+ arg_map["approximate"] = '"tanh"'
276
+ else:
277
+ arg_map["grad_output"] = "at::rand({22, 22, 22})"
278
+ arg_map["self"] = "at::rand({22, 22, 22})"
279
+ arg_map["approximate"] = '"tanh"'
280
+ return
281
+ if op_name == "index_add":
282
+ if index == 0:
283
+ arg_map["self"] = "at::rand({2})"
284
+ arg_map["dim"] = "0"
285
+ arg_map["index"] = "at::randint(0, 1, {2}, at::kInt)"
286
+ arg_map["source"] = "at::rand({2})"
287
+ arg_map["alpha"] = "2"
288
+ else:
289
+ arg_map["self"] = "at::rand({16})"
290
+ arg_map["dim"] = "0"
291
+ arg_map["index"] = "at::randint(0, 10, {16}, at::kInt)"
292
+ arg_map["source"] = "at::rand({16})"
293
+ arg_map["alpha"] = "2"
294
+ return
295
+ if op_name == "index_copy":
296
+ if index == 0:
297
+ arg_map["self"] = "at::rand({2})"
298
+ arg_map["dim"] = "0"
299
+ arg_map["index"] = "at::randint(0, 1, {2}, at::kLong)"
300
+ arg_map["source"] = "at::rand({2})"
301
+ else:
302
+ arg_map["self"] = "at::rand({32})"
303
+ arg_map["dim"] = "0"
304
+ arg_map["index"] = "at::randint(0, 10, {32}, at::kLong)"
305
+ arg_map["source"] = "at::rand({32})"
306
+ return
307
+ if op_name == "linalg_cross":
308
+ if index == 0:
309
+ arg_map["self"] = "at::rand({6, 3, 6})"
310
+ arg_map["other"] = "at::rand({6, 3, 6})"
311
+ arg_map["dim"] = "1"
312
+ else:
313
+ arg_map["self"] = "at::rand({22, 3, 22})"
314
+ arg_map["other"] = "at::rand({22, 3, 22})"
315
+ arg_map["dim"] = "1"
316
+ return
317
+ if op_name == "nll_loss_backward":
318
+ if index == 0:
319
+ arg_map["grad_output"] = "at::rand({})"
320
+ arg_map["self"] = "at::rand({6})"
321
+ arg_map["target"] = "at::randint(0, 5, {6}, torch::kInt64)"
322
+ arg_map["weight"] = "at::rand({6})"
323
+ arg_map["reduction"] = "1"
324
+ arg_map["ignore_index"] = "1"
325
+ arg_map["total_weight"] = "at::rand({})"
326
+ else:
327
+ arg_map["grad_output"] = "at::rand({})"
328
+ arg_map["self"] = "at::rand({36})"
329
+ arg_map["target"] = "at::randint(0, 11, {36}, torch::kInt64)"
330
+ arg_map["weight"] = "at::rand({36})"
331
+ arg_map["reduction"] = "1"
332
+ arg_map["ignore_index"] = "1"
333
+ arg_map["total_weight"] = "at::rand({})"
334
+ return
335
+ if op_name in ["scatter", "scatter_add", "_scatter_reduce"]:
336
+ if index == 0:
337
+ arg_map["self"] = "at::randint(1, 100, {2,2,2}, torch::kInt64)"
338
+ arg_map["index"] = "at::randint(0, 1, {2,2,2}, torch::kInt64)"
339
+ arg_map["src"] = "at::randint(1, 100, {2,2,2}, torch::kInt64)"
340
+ else:
341
+ arg_map["self"] = "at::randint(1, 100, {5,5,5}, torch::kInt64)"
342
+ arg_map["index"] = "at::randint(0, 1, {5,5,5}, torch::kInt64)"
343
+ arg_map["src"] = "at::randint(1, 100, {5,5,5}, torch::kInt64)"
344
+ if "reduce" in arg_map:
345
+ arg_map["reduce"] = '"sum"' if op_name == "_scatter_reduce" else '"add"'
346
+ return
347
+ if op_name == "scatter_reduce":
348
+ arg_map["reduce"] = '"mean"'
349
+ if index == 0:
350
+ arg_map["index"] = "at::randint(6, {6, 6, 6}, torch::kInt64)"
351
+ else:
352
+ arg_map["index"] = "at::randint(22, {22, 22, 22}, torch::kInt64)"
353
+ return
354
+ if op_name == "special_zeta":
355
+ if index == 0:
356
+ arg_map["self"] = "at::rand({2,2,2}, at::kDouble) + at::ones({2,2,2})"
357
+ arg_map["other"] = "at::rand({2,2,2}, at::kDouble) + at::ones({2,2,2})"
358
+ else:
359
+ arg_map["self"] = "at::rand({5,5,5}, at::kDouble) + at::ones({5,5,5})"
360
+ arg_map["other"] = "at::rand({5,5,5}, at::kDouble) + at::ones({5,5,5})"
361
+ return
362
+ if op_name == "_convert_indices_from_csr_to_coo":
363
+ if index == 0:
364
+ arg_map["crow_indices"] = "torch::tensor({1}, torch::kInt32)"
365
+ arg_map["col_indices"] = "torch::tensor({0, 1, 0}, torch::kInt32)"
366
+ arg_map["out_int32"] = "false"
367
+ else:
368
+ arg_map["crow_indices"] = "torch::tensor({0}, torch::kInt32)"
369
+ arg_map["col_indices"] = (
370
+ "torch::tensor({0, 1, 0, 2, 1, 2, 0, 1, 0, 2, 1, 2}, torch::kInt32)"
371
+ )
372
+ arg_map["out_int32"] = "false"
373
+ return
374
+ if op_name == "_convert_indices_from_coo_to_csr":
375
+ if index == 0:
376
+ arg_map["self"] = "at::randint(0, 3, {2}, at::kInt)"
377
+ arg_map["size"] = "10"
378
+ arg_map["out_int32"] = "false"
379
+ else:
380
+ arg_map["self"] = "at::randint(0, 3, {12}, at::kInt)"
381
+ arg_map["size"] = "24"
382
+ arg_map["out_int32"] = "false"
383
+ return
384
+ if op_name in ("diagonal", "linalg_diagonal"):
385
+ arg_map["offset"] = "0"
386
+ arg_map["dim1"] = "2"
387
+ arg_map["dim2"] = "1"
388
+ return
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torchgen/static_runtime/gen_static_runtime_ops.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import itertools
5
+ import os
6
+ from typing import TYPE_CHECKING, TypeVar, Union
7
+
8
+ from libfb.py.log import set_simple_logging # type: ignore[import]
9
+
10
+ from torchgen import gen
11
+ from torchgen.context import native_function_manager
12
+ from torchgen.model import DispatchKey, NativeFunctionsGroup, NativeFunctionsViewGroup
13
+ from torchgen.static_runtime import config, generator
14
+
15
+
16
+ if TYPE_CHECKING:
17
+ from collections.abc import Sequence
18
+
19
+
20
+ # Given a list of `grouped_native_functions` sorted by their op names, return a list of
21
+ # lists each of which groups ops that share the base name. For example, `mean` and
22
+ # `mean.dim` are grouped together by this function.
23
+
24
+ NativeGroupT = TypeVar(
25
+ "NativeGroupT",
26
+ bound=Union[NativeFunctionsGroup, NativeFunctionsViewGroup],
27
+ )
28
+
29
+
30
+ def group_functions_by_op_name(
31
+ grouped_native_functions: Sequence[NativeGroupT],
32
+ ) -> Sequence[Sequence[NativeGroupT]]:
33
+ if not grouped_native_functions:
34
+ return []
35
+ groups = []
36
+
37
+ def is_supported(g: NativeFunctionsGroup | NativeFunctionsViewGroup) -> bool:
38
+ with native_function_manager(g):
39
+ return generator.is_supported(g)
40
+
41
+ eligible_ops = (g for g in grouped_native_functions if is_supported(g))
42
+ groups = [
43
+ list(group)
44
+ for k, group in (
45
+ itertools.groupby(
46
+ eligible_ops,
47
+ key=config.func_name_base_str,
48
+ )
49
+ )
50
+ ]
51
+
52
+ return groups
53
+
54
+
55
+ def clang_format(cpp_file_path: str) -> None:
56
+ import subprocess
57
+
58
+ subprocess.check_call(["clang-format", "-i", cpp_file_path])
59
+
60
+
61
+ def write_cpp(cpp_ops: Sequence[str], file_path: str) -> None:
62
+ code = "\n".join(cpp_ops)
63
+ generated = f"""// @lint-ignore-every CLANGTIDY HOWTOEVEN
64
+ // AUTO-GENERATED FROM: torchgen/static_runtime/gen_static_runtime_ops.py
65
+ #include <torch/csrc/jit/runtime/static/ops.h>
66
+
67
+ #include <ATen/CPUFunctions.h>
68
+ #include <ATen/InferSize.h>
69
+ #include <ATen/NativeFunctions.h>
70
+ #include <ATen/Parallel.h>
71
+ #include <ATen/ScalarOps.h>
72
+ #include <ATen/TensorUtils.h>
73
+ #include <ATen/cpu/vec/functional.h>
74
+ #include <ATen/cpu/vec/vec.h>
75
+ #include <ATen/native/EmbeddingBag.h>
76
+ #include <ATen/native/Fill.h>
77
+ #include <ATen/native/IndexingUtils.h>
78
+ #include <ATen/native/NonSymbolicBC.h>
79
+ #include <ATen/native/Resize.h>
80
+ #include <ATen/native/SharedReduceOps.h>
81
+ #include <ATen/native/TensorAdvancedIndexing.h>
82
+ #include <ATen/native/cpu/SerialStackImpl.h>
83
+ #include <ATen/native/layer_norm.h>
84
+ #include <ATen/native/quantized/cpu/fbgemm_utils.h>
85
+ #include <ATen/native/quantized/cpu/qembeddingbag.h>
86
+ #include <ATen/native/quantized/cpu/qembeddingbag_prepack.h>
87
+ #include <ATen/quantized/QTensorImpl.h>
88
+ #include <ATen/quantized/Quantizer.h>
89
+ #include <c10/core/ScalarType.h>
90
+ #include <c10/core/WrapDimMinimal.h>
91
+ #include <c10/util/irange.h>
92
+ #include <torch/csrc/jit/ir/ir.h>
93
+ #include <torch/csrc/jit/runtime/static/impl.h>
94
+ #include <torch/csrc/jit/runtime/static/te_wrapper.h>
95
+ #include <torch/csrc/jit/runtime/vararg_functions.h>
96
+ #include <torch/csrc/jit/tensorexpr/ir.h>
97
+ #include <torch/csrc/jit/tensorexpr/ir_simplifier.h>
98
+ #include <torch/csrc/jit/tensorexpr/llvm_codegen.h>
99
+ #include <torch/csrc/jit/tensorexpr/loopnest.h>
100
+
101
+ namespace torch {{
102
+ namespace jit {{
103
+
104
+ {code}
105
+
106
+ }} // namespace jit
107
+ }} // namespace torch
108
+ """
109
+ with open(file_path, "w") as f:
110
+ f.write(generated)
111
+ clang_format(file_path)
112
+
113
+
114
+ def write_test_cpp(cpp_ops: Sequence[str], file_path: str) -> None:
115
+ code = "\n".join(cpp_ops)
116
+ generated = f"""// @lint-ignore-every CLANGTIDY HOWTOEVEN
117
+ // AUTO-GENERATED FROM: torchgen/static_runtime/gen_static_runtime_ops.py
118
+ #include <gtest/gtest.h>
119
+ #include <torch/csrc/jit/runtime/static/impl.h>
120
+ #include <torch/torch.h>
121
+
122
+ #include "test_utils.h"
123
+
124
+ using namespace caffe2;
125
+ using namespace torch;
126
+ using namespace torch::jit;
127
+ using namespace torch::jit::test;
128
+ using c10::IValue;
129
+
130
+ {code}
131
+
132
+ """
133
+ with open(file_path, "w") as f:
134
+ f.write(generated)
135
+ clang_format(file_path)
136
+
137
+
138
+ def main() -> None:
139
+ parser = argparse.ArgumentParser(description="Generate ATen source files")
140
+ parser.add_argument(
141
+ "-s",
142
+ "--source-path",
143
+ help="path to source directory for ATen",
144
+ default="caffe2/aten/src/ATen",
145
+ )
146
+ parser.add_argument(
147
+ "-p",
148
+ "--generated-ops-cpp-path",
149
+ help="path to directory to generate op dispatcher .cpp file",
150
+ default="caffe2/torch/csrc/jit/runtime/static/generated_ops.cpp",
151
+ )
152
+ parser.add_argument(
153
+ "-t",
154
+ "--generated-ops-test-cpp-path",
155
+ help="path to directory to generate op dispatcher .cpp file",
156
+ default="caffe2/benchmarks/static_runtime/test_generated_ops.cc",
157
+ )
158
+ options = parser.parse_args()
159
+ native_yaml_path = os.path.join(options.source_path, "native/native_functions.yaml")
160
+ tags_yaml_path = os.path.join(options.source_path, "native/tags.yaml")
161
+ parsed_yaml = gen.parse_native_yaml(native_yaml_path, tags_yaml_path)
162
+ native_functions, backend_indices = (
163
+ parsed_yaml.native_functions,
164
+ parsed_yaml.backend_indices,
165
+ )
166
+
167
+ op_generator = generator.GenOpDispatcher()
168
+ test_case_generator = generator.GenOpTestCase()
169
+
170
+ native_functions_groups = [
171
+ g
172
+ for g in gen.get_grouped_native_functions(native_functions)
173
+ if isinstance(g, NativeFunctionsGroup)
174
+ ]
175
+
176
+ supported_functions_groups = group_functions_by_op_name(native_functions_groups)
177
+
178
+ out_variant_op_result = [
179
+ op_generator.out_variant(groups, backend_indices[DispatchKey.CPU])
180
+ for groups in supported_functions_groups
181
+ ]
182
+ out_variant_test_result = [
183
+ test_case_generator.out_variant(groups) for groups in supported_functions_groups
184
+ ]
185
+
186
+ native_functions_view_groups = [
187
+ g
188
+ for g in gen.get_grouped_by_view_native_functions(native_functions)
189
+ if isinstance(g, NativeFunctionsViewGroup)
190
+ ]
191
+
192
+ supported_functions_view_groups = group_functions_by_op_name(
193
+ native_functions_view_groups
194
+ )
195
+
196
+ view_op_result = [
197
+ op_generator.view(groups, backend_indices[DispatchKey.CPU])
198
+ for groups in supported_functions_view_groups
199
+ ]
200
+ view_test_result = [
201
+ test_case_generator.view(groups) for groups in supported_functions_view_groups
202
+ ]
203
+
204
+ op_result = out_variant_op_result + ["\n\n"] + view_op_result
205
+ test_result = out_variant_test_result + ["\n\n"] + view_test_result
206
+
207
+ write_cpp(op_result, options.generated_ops_cpp_path)
208
+ write_test_cpp(test_result, options.generated_ops_test_cpp_path)
209
+
210
+ print(
211
+ f"\ntotal grouped native ops: {len(gen.get_grouped_native_functions(native_functions)):d}"
212
+ )
213
+
214
+ print(f"grouped native ops with out variant: {len(native_functions_groups):d}")
215
+ supported_functions_num = sum(len(groups) for groups in supported_functions_groups)
216
+ print(f"generated functions groups with out variant: {supported_functions_num:d}")
217
+
218
+ print(f"\nview grouped native ops: {len(native_functions_view_groups):d}")
219
+ supported_view_functions_num = sum(
220
+ len(groups) for groups in supported_functions_view_groups
221
+ )
222
+ print(f"generated functions view groups: {supported_view_functions_num:d}")
223
+
224
+ print(
225
+ f"\noverall generated : {supported_functions_num + supported_view_functions_num:d}"
226
+ )
227
+
228
+
229
+ if __name__ == "__main__":
230
+ set_simple_logging(escape_newlines=False)
231
+ main()
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torchgen/static_runtime/generator.py ADDED
@@ -0,0 +1,814 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import logging
5
+ import math
6
+ from typing import TYPE_CHECKING
7
+
8
+ import torchgen.api.cpp as cpp
9
+ from torchgen.context import native_function_manager
10
+ from torchgen.model import (
11
+ Argument,
12
+ BackendIndex,
13
+ BaseTy,
14
+ BaseType,
15
+ FunctionSchema,
16
+ NativeFunctionsGroup,
17
+ NativeFunctionsViewGroup,
18
+ OptionalType,
19
+ SelfArgument,
20
+ TensorOptionsArguments,
21
+ Type,
22
+ )
23
+ from torchgen.static_runtime import config
24
+
25
+
26
+ if TYPE_CHECKING:
27
+ from collections.abc import Sequence
28
+
29
+
30
+ logger: logging.Logger = logging.getLogger()
31
+
32
+
33
+ def has_alias(
34
+ arguments: Sequence[Argument | SelfArgument | TensorOptionsArguments],
35
+ ) -> bool:
36
+ for arg in arguments:
37
+ annotation = getattr(arg, "annotation", None)
38
+ if not annotation:
39
+ continue
40
+ alias_set = getattr(annotation, "alias_set", ())
41
+ if alias_set:
42
+ return True
43
+ return False
44
+
45
+
46
+ BLOCKED_OPS = frozenset(
47
+ (
48
+ # non cpu ops
49
+ "sparse_sampled_addmm",
50
+ "hspmm",
51
+ "linalg_svdvals",
52
+ # sparse ops
53
+ "sspaddmm",
54
+ "coalesce",
55
+ "_indices",
56
+ "indices",
57
+ "_values",
58
+ "values",
59
+ "crow_indices",
60
+ "col_indices",
61
+ # deprecated ops
62
+ "floor_divide",
63
+ "ger",
64
+ # buggy ops
65
+ "conj_physical", # P495807361
66
+ "binary_cross_entropy", # P496394764
67
+ "arccosh",
68
+ # uncommon ops
69
+ "cholesky",
70
+ "lu_solve",
71
+ "linalg_cholesky",
72
+ "linalg_householder_product",
73
+ "linalg_ldl_solve",
74
+ "_compute_linear_combination",
75
+ # training related ops
76
+ "_make_dual",
77
+ # cannot call directly
78
+ "_fw_primal",
79
+ # no documentation
80
+ "_index_reduce",
81
+ # TODO: these ones got added recently and need manual inspection
82
+ "_new_zeros_with_same_feature_meta",
83
+ "_conj_physical",
84
+ "binary_cross_entropy_with_logits",
85
+ "bincount",
86
+ "conv_tbc",
87
+ "copy",
88
+ "_copy_from",
89
+ "_copy_from_and_resize",
90
+ "count_nonzero",
91
+ "cudnn_affine_grid_generator",
92
+ "cudnn_affine_grid_generator_backward",
93
+ "cudnn_grid_sampler",
94
+ "diag_embed",
95
+ "embedding",
96
+ "embedding_dense_backward",
97
+ "_embedding_bag_dense_backward",
98
+ "_embedding_bag_per_sample_weights_backward",
99
+ "grid_sampler_2d",
100
+ "_grid_sampler_2d_cpu_fallback",
101
+ "grid_sampler_3d",
102
+ "isnan",
103
+ "mkldnn_linear",
104
+ "median",
105
+ "nanmedian",
106
+ "_sparse_sparse_matmul",
107
+ "batch_norm_backward_elemt",
108
+ "_euclidean_dist",
109
+ "pixel_shuffle",
110
+ "pixel_unshuffle",
111
+ "channel_shuffle",
112
+ "_reshape_nested_backward",
113
+ "relu",
114
+ "prelu",
115
+ "celu",
116
+ "slice_scatter",
117
+ "select_scatter",
118
+ "diagonal_scatter",
119
+ "sum",
120
+ "_mkldnn_transpose",
121
+ "_nested_tensor_from_mask",
122
+ "_nested_from_padded",
123
+ "_nested_tensor_size",
124
+ "_nested_from_padded_and_nested_example",
125
+ "_standard_gamma_grad",
126
+ "_dirichlet_grad",
127
+ "native_norm",
128
+ "_sparse_softmax",
129
+ "_sparse_softmax_backward_data",
130
+ "_sparse_log_softmax",
131
+ "_sparse_log_softmax_backward_data",
132
+ "zero",
133
+ "_sparse_addmm",
134
+ "sparse_mask",
135
+ "_sparse_mask_projection",
136
+ "_to_dense",
137
+ "_coalesce",
138
+ "_coalesced",
139
+ "copy_sparse_to_sparse",
140
+ "to_sparse",
141
+ "to_sparse_csr",
142
+ "to_sparse_csc",
143
+ "to_mkldnn",
144
+ "quantize_per_tensor_dynamic",
145
+ "quantize_per_channel",
146
+ "q_per_channel_scales",
147
+ "q_per_channel_zero_points",
148
+ "int_repr",
149
+ "_make_per_channel_quantized_tensor",
150
+ "set",
151
+ "lift",
152
+ "lift_fresh",
153
+ "lift_fresh_copy",
154
+ "masked_scatter",
155
+ "_masked_softmax",
156
+ "_masked_softmax_backward",
157
+ "put",
158
+ "index_reduce",
159
+ "trace",
160
+ "_cholesky_solve_helper",
161
+ "dist",
162
+ "max",
163
+ "_torch_cuda_cu_linker_symbol_op",
164
+ "glu_jvp",
165
+ "glu_backward_jvp",
166
+ "hardswish_backward",
167
+ "rrelu_with_noise_backward",
168
+ "mkldnn_adaptive_avg_pool2d_backward",
169
+ "_adaptive_avg_pool2d_backward",
170
+ "_adaptive_avg_pool3d_backward",
171
+ "isinf",
172
+ "linalg_lu_solve",
173
+ "linalg_vecdot",
174
+ "linalg_matrix_exp",
175
+ "linalg_eigvalsh",
176
+ "_test_warn_in_autograd",
177
+ "_test_autograd_multiple_dispatch_view",
178
+ "_test_autograd_multiple_dispatch_view_copy",
179
+ "_segment_reduce",
180
+ "_segment_reduce_backward",
181
+ "_fw_primal_copy",
182
+ "_make_dual_copy",
183
+ "view_as_real_copy",
184
+ "view_as_complex_copy",
185
+ "_conj_copy",
186
+ "_neg_view_copy",
187
+ "diagonal_copy",
188
+ "detach_copy",
189
+ "squeeze_copy",
190
+ "t_copy",
191
+ "unsqueeze_copy",
192
+ "_indices_copy",
193
+ "_values_copy",
194
+ "indices_copy",
195
+ "values_copy",
196
+ "crow_indices_copy",
197
+ "col_indices_copy",
198
+ "ccol_indices",
199
+ "ccol_indices_copy",
200
+ "row_indices",
201
+ "row_indices_copy",
202
+ "unfold_copy",
203
+ "alias_copy",
204
+ "_triton_multi_head_attention",
205
+ "special_airy_ai",
206
+ "special_bessel_j0",
207
+ "special_bessel_j1",
208
+ "special_bessel_y0",
209
+ "special_bessel_y1",
210
+ "special_chebyshev_polynomial_t",
211
+ "special_chebyshev_polynomial_u",
212
+ "special_chebyshev_polynomial_v",
213
+ "special_chebyshev_polynomial_w",
214
+ "special_hermite_polynomial_h",
215
+ "special_hermite_polynomial_he",
216
+ "special_laguerre_polynomial_l",
217
+ "special_legendre_polynomial_p",
218
+ "special_modified_bessel_i0",
219
+ "special_modified_bessel_i1",
220
+ "special_modified_bessel_k0",
221
+ "special_modified_bessel_k1",
222
+ "special_scaled_modified_bessel_k0",
223
+ "special_scaled_modified_bessel_k1",
224
+ "special_shifted_chebyshev_polynomial_t",
225
+ "special_shifted_chebyshev_polynomial_u",
226
+ "special_shifted_chebyshev_polynomial_v",
227
+ "special_shifted_chebyshev_polynomial_w",
228
+ "special_spherical_bessel_j0",
229
+ "_foobar",
230
+ "_nested_tensor_strides",
231
+ "_nested_tensor_storage_offsets",
232
+ "_nested_get_values", # no CPU backend
233
+ "_nested_get_values_copy", # no CPU backend
234
+ "_nested_view_from_jagged", # testing needs to be patched
235
+ "_nested_view_from_jagged_copy", # testing needs to be patched
236
+ "_nested_view_from_buffer", # testing needs to be patched
237
+ "_nested_view_from_buffer_copy", # testing needs to be patched
238
+ "_int_mm", # testing needs to be patched
239
+ "_to_sparse_csc", # testing needs to be patched
240
+ "_to_sparse_csr", # testing needs to be patched
241
+ "segment_reduce", # testing needs to be patched
242
+ )
243
+ )
244
+
245
+
246
+ def is_supported(g: NativeFunctionsGroup | NativeFunctionsViewGroup) -> bool:
247
+ base_op_name = ""
248
+ func = None
249
+ if isinstance(g, NativeFunctionsViewGroup):
250
+ base_op_name = g.view.root_name
251
+ func = g.view.func
252
+ else:
253
+ base_op_name = g.out.func.name.name.base
254
+ func = g.out.func
255
+ if config.is_hand_written(g):
256
+ logger.info("HAND WRITTEN: %s", base_op_name)
257
+ return False
258
+ if base_op_name in BLOCKED_OPS:
259
+ logger.info("BLOCKED: %s", base_op_name)
260
+ return False
261
+ for arg in func.schema_order_arguments():
262
+ maybe_method = ivalue_type_conversion_method(arg.type)
263
+ if not maybe_method:
264
+ # Type converting is unsupported yet.
265
+ logger.info("NOT SUPPORTED TYPE CONVERTING: %s", func)
266
+ return False
267
+
268
+ if isinstance(g, NativeFunctionsViewGroup):
269
+ # TODO: stop doing type tests by converting to C++ and then testing
270
+ # the string, just test the dang thing directly
271
+ if "at::Tensor" != cpp.returns_type(func.returns, symint=False).cpp_type():
272
+ # Returns a non-Tensor value.
273
+ logger.info("NON-TENSOR RET TYPE: %s", str(func))
274
+ return False
275
+ return True
276
+
277
+ # For out variant ops, we need to check the arguments of its functional func.
278
+ for arg in g.functional.func.schema_order_arguments():
279
+ maybe_method = ivalue_type_conversion_method(arg.type)
280
+ if not maybe_method:
281
+ # Type converting is unsupported yet.
282
+ logger.info("NOT SUPPORTED TYPE CONVERTING: %s", g.functional.func)
283
+ return False
284
+
285
+ if not g.structured:
286
+ # In case of unstructured op, we check if it has out variant implementation.
287
+ # The out variant implementation satisfies the minimum requirement that it has the output tensor as the last
288
+ # parameter.
289
+ if (
290
+ not hasattr(g, "out")
291
+ or not str(func).endswith("Tensor(a!) out) -> Tensor(a!)")
292
+ or not str(func.name).endswith(".out")
293
+ ):
294
+ return False
295
+ # TODO: stop type testing by converting to C++
296
+ if "at::Tensor &" != cpp.returns_type(func.returns, symint=False).cpp_type():
297
+ logger.info("NON_TENSOR RET TYPE: %s", func)
298
+ return False
299
+ if has_alias(func.arguments.non_out):
300
+ # This op may create an alias of inputs.
301
+ logger.info("INPUTS ALIAS: %s", base_op_name)
302
+ return False
303
+ return True
304
+
305
+
306
+ def ivalue_type_conversion_method(
307
+ arg_type: BaseType | OptionalType | Type,
308
+ ) -> tuple[bool, str] | None:
309
+ """
310
+ Return the method call expression of `c10::ivalue' to convert its contained value to
311
+ the expected value of `arg_type` type. For example, for `arg_type` == BaseTy.Tensor,
312
+ this function returns ".toTensor()", so that it can be appended to the ivalue's
313
+ variable name to get the value of the expected type.
314
+ """
315
+ type_conversion_methods = {
316
+ BaseTy.Tensor: ((True, "toTensor()"), (False, "toOptional<at::Tensor>()")),
317
+ BaseTy.int: ((False, "toInt()"), (False, "toOptional<int64_t>()")),
318
+ BaseTy.bool: ((False, "toBool()"), (False, "toOptional<bool>()")),
319
+ BaseTy.Scalar: ((False, "toScalar()"), (False, "toOptional<at::Scalar>()")),
320
+ BaseTy.ScalarType: (
321
+ (False, "toScalarType()"),
322
+ (False, "toOptional<at::ScalarType>()"),
323
+ ),
324
+ BaseTy.str: (
325
+ (False, "toStringView()"),
326
+ (False, "toOptional<c10::string_view>()"),
327
+ (False, "toOptional<::std::string_view>()"),
328
+ ),
329
+ }
330
+
331
+ base_ty_object = None
332
+ if isinstance(arg_type, BaseType):
333
+ base_ty_object = arg_type.name
334
+ elif isinstance(arg_type, OptionalType):
335
+ if not isinstance(arg_type.elem, BaseType):
336
+ # ListType is currently unsupported.
337
+ return None
338
+ base_ty_object = arg_type.elem.name
339
+ else:
340
+ return None
341
+
342
+ if base_ty_object not in type_conversion_methods:
343
+ return None
344
+ methods = type_conversion_methods[base_ty_object]
345
+ if isinstance(arg_type, BaseType):
346
+ return methods[0]
347
+ return methods[1]
348
+
349
+
350
+ should_use_int_tensor_ops_ = frozenset(
351
+ (
352
+ "bitwise_not",
353
+ "bitwise_and",
354
+ "bitwise_or",
355
+ "bitwise_xor",
356
+ "bitwise_left_shift",
357
+ "bitwise_right_shift",
358
+ "gcd",
359
+ "lcm",
360
+ "scatter",
361
+ "gather",
362
+ "_convert_indices_from_coo_to_csr",
363
+ "_convert_indices_from_csr_to_coo",
364
+ )
365
+ )
366
+ should_use_complex_tensor_ops_ = frozenset(("view_as_real", "imag", "_conj"))
367
+
368
+
369
+ def should_use_int_tensor(op_name: str) -> bool:
370
+ return op_name in should_use_int_tensor_ops_
371
+
372
+
373
+ def should_use_complex_tensor(op_name: str) -> bool:
374
+ return op_name in should_use_complex_tensor_ops_
375
+
376
+
377
+ test_tensor_dim_ops_1_ = frozenset(
378
+ (
379
+ "addmv",
380
+ "index_add",
381
+ "_convert_indices_from_coo_to_csr",
382
+ "_convert_indices_from_csr_to_coo",
383
+ "nll_loss_backward",
384
+ "dot",
385
+ "vdot",
386
+ "outer",
387
+ "ger",
388
+ )
389
+ )
390
+ test_tensor_dim_ops_2_ = frozenset(
391
+ ("addmm", "mm", "nuclear_norm", "diag", "_addmm_activation", "matrix_H", "t")
392
+ )
393
+
394
+
395
+ def test_tensor_dim(op_name: str) -> int:
396
+ if op_name in test_tensor_dim_ops_1_:
397
+ return 1
398
+ if op_name in test_tensor_dim_ops_2_:
399
+ return 2
400
+ return 3
401
+
402
+
403
+ test_tensor_shapes_string = '{"view_as_complex": "{2, 2}"}'
404
+ test_tensor_shape_json: dict[str, str] = json.loads(test_tensor_shapes_string)
405
+
406
+
407
+ def test_tensor_shape(op_name: str) -> str:
408
+ if op_name in test_tensor_shape_json:
409
+ return test_tensor_shape_json[op_name]
410
+ else:
411
+ return ""
412
+
413
+
414
+ def test_value_expression(
415
+ arg_type: BaseType | OptionalType | Type, index: int, op_name: str
416
+ ) -> str:
417
+ tensor_size_ex = test_tensor_shape(op_name)
418
+ if tensor_size_ex == "":
419
+ num_tensors = 16 if index == 0 else 64
420
+ num_dim = test_tensor_dim(op_name)
421
+ size_per_dim = math.ceil(num_tensors / float(num_dim))
422
+ size_per_dim += size_per_dim % 2
423
+ tensor_size_ex = "{{{}}}".format(",".join([f"{size_per_dim}"] * num_dim))
424
+ if should_use_int_tensor(op_name):
425
+ tensor_expression = f"at::randint(1, 100, {tensor_size_ex}, at::kInt)"
426
+ elif should_use_complex_tensor(op_name):
427
+ tensor_expression = f"at::randn({tensor_size_ex}, at::kComplexFloat)"
428
+ else:
429
+ tensor_expression = f"at::rand({tensor_size_ex})"
430
+
431
+ value_expressions = {
432
+ BaseTy.Tensor: tensor_expression,
433
+ BaseTy.int: "1",
434
+ BaseTy.bool: "false",
435
+ BaseTy.Scalar: "2",
436
+ BaseTy.ScalarType: "at::ScalarType::Float",
437
+ BaseTy.str: '"floor"',
438
+ }
439
+
440
+ base_ty_object = None
441
+ if isinstance(arg_type, BaseType):
442
+ base_ty_object = arg_type.name
443
+ else:
444
+ assert isinstance(arg_type, OptionalType) and isinstance(
445
+ arg_type.elem, BaseType
446
+ )
447
+ base_ty_object = arg_type.elem.name
448
+ assert base_ty_object in value_expressions, "not expected type"
449
+ value_expression = value_expressions[base_ty_object]
450
+ return value_expression
451
+
452
+
453
+ def generate_test_value_definitions(schema: FunctionSchema, index: int) -> str:
454
+ assert not schema.is_out_fn()
455
+ schema_name = schema.name.name.base
456
+ arg_map = {}
457
+ for arg in schema.schema_order_arguments():
458
+ test_value_exp = test_value_expression(arg.type, index, schema_name)
459
+ arg_map[arg.name] = test_value_exp
460
+ config.override_test_values(arg_map, schema_name, index)
461
+ arg_populations = []
462
+ for arg_name, arg_value in arg_map.items():
463
+ arg_populations.append(f"auto {arg_name}{index} = {arg_value}")
464
+ return ";\n ".join(arg_populations) + ";"
465
+
466
+
467
+ def generate_test_value_names(schema: FunctionSchema, index: int) -> str:
468
+ assert not schema.is_out_fn()
469
+ return ",".join(f"{arg.name}{index}" for arg in schema.schema_order_arguments())
470
+
471
+
472
+ generate_test_ir_arguments_base_ty_to_type_str_ = {
473
+ BaseTy.Tensor: "Tensor",
474
+ BaseTy.int: "int",
475
+ BaseTy.float: "float",
476
+ BaseTy.str: "str",
477
+ BaseTy.Scalar: "int",
478
+ BaseTy.ScalarType: "int",
479
+ BaseTy.bool: "bool",
480
+ }
481
+
482
+
483
+ def generate_test_ir_arguments(
484
+ schema: FunctionSchema,
485
+ ) -> list[tuple[str, str | None]]:
486
+ def ir_argument(arg: Argument) -> tuple[str, str | None]:
487
+ t = arg.type
488
+ add_optional = False
489
+ if isinstance(t, OptionalType):
490
+ t = t.elem
491
+ add_optional = True
492
+ assert isinstance(t, BaseType)
493
+ type_str = None
494
+ if t.name in generate_test_ir_arguments_base_ty_to_type_str_:
495
+ type_str = generate_test_ir_arguments_base_ty_to_type_str_[t.name]
496
+ if type_str and add_optional:
497
+ type_str = f"{type_str}?"
498
+ return ("%" + arg.name, type_str)
499
+
500
+ return [ir_argument(arg) for arg in schema.schema_order_arguments()]
501
+
502
+
503
+ def generate_arg_extraction(schema: FunctionSchema) -> str:
504
+ arg_populations = []
505
+ for i, arg in enumerate(schema.schema_order_arguments()):
506
+ maybe_method = ivalue_type_conversion_method(arg.type)
507
+ assert maybe_method
508
+ is_reference, type_conversion_method = maybe_method
509
+ reference = "&" if is_reference else ""
510
+ arg_populations.append(
511
+ f"const auto{reference} {arg.name} = p_node->Input({i}).{type_conversion_method}"
512
+ )
513
+ return ";\n ".join(arg_populations) + ";"
514
+
515
+
516
+ def get_kernel_name(g: NativeFunctionsGroup, backend_index: BackendIndex) -> str:
517
+ kernel = backend_index.get_kernel(g.functional)
518
+ if g.structured or kernel is None:
519
+ return cpp.name(g.functional.func)
520
+ return kernel.kernel
521
+
522
+
523
+ def get_out_kernel_name(g: NativeFunctionsGroup, backend_index: BackendIndex) -> str:
524
+ kernel = backend_index.get_kernel(g.out)
525
+ if g.structured or kernel is None:
526
+ return cpp.name(g.out.func)
527
+ return kernel.kernel
528
+
529
+
530
+ def generate_non_out_variant_call(
531
+ g: NativeFunctionsGroup, backend_index: BackendIndex
532
+ ) -> str:
533
+ schema = g.functional.func
534
+ assert not schema.is_out_fn()
535
+ kernel_name = get_kernel_name(g, backend_index)
536
+ arg_names = (arg.name for arg in schema.schema_order_arguments())
537
+ namespace_name = "cpu" if g.structured else "native"
538
+ return f"at::{namespace_name}::{kernel_name}({','.join(arg_names)})"
539
+
540
+
541
+ def generate_call_to_view_ops(
542
+ g: NativeFunctionsViewGroup, backend_index: BackendIndex
543
+ ) -> str:
544
+ schema = g.view.func
545
+ kernel_name = cpp.name(schema)
546
+ kernel = backend_index.get_kernel(g.view)
547
+ if kernel:
548
+ kernel_name = kernel.kernel
549
+ arg_names = (arg.name for arg in schema.schema_order_arguments())
550
+ namespace_name = "native"
551
+ return f"at::{namespace_name}::{kernel_name}({','.join(arg_names)})"
552
+
553
+
554
+ def generate_out_variant_call(
555
+ g: NativeFunctionsGroup, backend_index: BackendIndex
556
+ ) -> str:
557
+ schema = g.out.func
558
+ assert schema.is_out_fn()
559
+ arg_names = []
560
+ kernel_name = get_out_kernel_name(g, backend_index)
561
+ if g.structured:
562
+ # structured op starts with the output tensor argument.
563
+ arg_names = [out_arg.name for out_arg in schema.arguments.out]
564
+ else:
565
+ arg_names = []
566
+ for arg in schema.arguments.non_out:
567
+ if isinstance(arg, SelfArgument):
568
+ arg_names.append(arg.argument.name)
569
+ else:
570
+ assert isinstance(arg, Argument)
571
+ arg_names.append(arg.name)
572
+ if not g.structured:
573
+ assert len(schema.arguments.out) == 1
574
+ arg_names.append(schema.arguments.out[0].name)
575
+ cpp_arg_names = ",".join(arg_names)
576
+ namespace_name = "cpu" if g.structured else "native"
577
+ return f"at::{namespace_name}::{kernel_name}({cpp_arg_names})"
578
+
579
+
580
+ no_memory_resize_ops = frozenset(
581
+ (
582
+ "isin.Scalar_Tensor",
583
+ "index_add",
584
+ "dot",
585
+ "vdot",
586
+ "nuclear_norm",
587
+ "histc",
588
+ "l1_loss",
589
+ "multi_margin_loss",
590
+ "multilabel_margin_loss",
591
+ "nll_loss",
592
+ "nll_loss2d",
593
+ "prod",
594
+ )
595
+ )
596
+
597
+
598
+ def should_check_resize(schema: FunctionSchema) -> bool:
599
+ schema_str = str(schema)
600
+ type_variant_op_name = schema_str[: schema_str.find("(")]
601
+ return type_variant_op_name not in no_memory_resize_ops
602
+
603
+
604
+ def op_name_from_group(g: NativeFunctionsGroup) -> str:
605
+ return g.functional.func.name.name.base
606
+
607
+
608
+ class GenOpDispatcher:
609
+ def out_variant(
610
+ self, groups: Sequence[NativeFunctionsGroup], backend_index: BackendIndex
611
+ ) -> str:
612
+ if not groups:
613
+ return ""
614
+ generated_type_variants = []
615
+ for g in groups:
616
+ with native_function_manager(g):
617
+ assert is_supported(g)
618
+ assert isinstance(g, NativeFunctionsGroup)
619
+ generated_type_variant = self.out_variant_op_generator(g, backend_index)
620
+ generated_type_variants.append(generated_type_variant)
621
+ op_name = op_name_from_group(groups[0])
622
+ body = "\n".join(generated_type_variants)
623
+ generated = f"""
624
+ REGISTER_OPERATOR_FUNCTOR(
625
+ aten::{op_name},
626
+ aten_{op_name},
627
+ [](Node* n) -> SROperator {{
628
+ {body}
629
+ LogAndDumpSchema(n);
630
+ return nullptr;
631
+ }})
632
+ """
633
+ return generated
634
+
635
+ def view(
636
+ self, groups: Sequence[NativeFunctionsViewGroup], backend_index: BackendIndex
637
+ ) -> str:
638
+ if not groups:
639
+ return ""
640
+ generated_type_variants = []
641
+ for g in groups:
642
+ with native_function_manager(g):
643
+ assert is_supported(g)
644
+ assert isinstance(g, NativeFunctionsViewGroup)
645
+ generated_type_variant = self.view_op_generator(g, backend_index)
646
+ generated_type_variants.append(generated_type_variant)
647
+ op_name = config.func_name_base_str(groups[0])
648
+ body = "\n".join(generated_type_variants)
649
+ generated = f"""
650
+ REGISTER_NATIVE_OPERATOR_FUNCTOR(
651
+ aten::{op_name},
652
+ aten_{op_name},
653
+ [](Node* n) -> SROperator {{
654
+ {body}
655
+ LogAndDumpSchema(n);
656
+ return nullptr;
657
+ }});
658
+ """
659
+ return generated
660
+
661
+ def out_variant_op_generator(
662
+ self, g: NativeFunctionsGroup, backend_index: BackendIndex
663
+ ) -> str:
664
+ functional = g.functional
665
+ schema = str(functional.func)
666
+ populated_argument = generate_arg_extraction(g.functional.func)
667
+ functional_variant_call = generate_non_out_variant_call(g, backend_index)
668
+ assert len(g.out.func.arguments.out) == 1
669
+ out_variable_name = str(g.out.func.arguments.out[0].name)
670
+ out_variant_call = generate_out_variant_call(g, backend_index)
671
+ generated = f"""
672
+ if (n->matches(torch::schema("aten::{schema}"))) {{
673
+ return [](ProcessedNode* p_node) {{
674
+ {populated_argument}
675
+ if (p_node->Output(0).isNone()) {{
676
+ p_node->Output(0) = {functional_variant_call};
677
+ return;
678
+ }}
679
+ auto& {out_variable_name} = p_node->Output(0).toTensor();
680
+ fastResizeToZero({out_variable_name});
681
+ {out_variant_call};
682
+ }};
683
+ }}"""
684
+ return generated
685
+
686
+ def view_op_generator(
687
+ self, g: NativeFunctionsViewGroup, backend_index: BackendIndex
688
+ ) -> str:
689
+ schema = str(g.view.func)
690
+ populated_argument = generate_arg_extraction(g.view.func)
691
+ functional_variant_call = generate_call_to_view_ops(g, backend_index)
692
+ generated = f"""
693
+ if (n->matches(torch::schema("aten::{schema}"))) {{
694
+ return [](ProcessedNode* p_node) {{
695
+ {populated_argument}
696
+ p_node->Output(0) = {functional_variant_call};
697
+ }};
698
+ }}"""
699
+ return generated
700
+
701
+
702
+ class GenOpTestCase:
703
+ def out_variant(self, groups: Sequence[NativeFunctionsGroup]) -> str:
704
+ if not groups:
705
+ return ""
706
+ generated_type_variants = []
707
+ for g in groups:
708
+ with native_function_manager(g):
709
+ assert is_supported(g)
710
+ assert isinstance(g, NativeFunctionsGroup)
711
+ generated_type_variant = self.out_variant_op_test_case_generator(g)
712
+ generated_type_variants.append(generated_type_variant)
713
+ return "\n".join(generated_type_variants)
714
+
715
+ def view(self, groups: Sequence[NativeFunctionsViewGroup]) -> str:
716
+ if not groups:
717
+ return ""
718
+ generated_type_variants = []
719
+ for g in groups:
720
+ with native_function_manager(g):
721
+ assert is_supported(g)
722
+ assert isinstance(g, NativeFunctionsViewGroup)
723
+ generated_type_variant = self.view_op_test_case_generator(g)
724
+ generated_type_variants.append(generated_type_variant)
725
+ return "\n".join(generated_type_variants)
726
+
727
+ def out_variant_op_test_case_generator(self, g: NativeFunctionsGroup) -> str:
728
+ schema = g.functional.func
729
+ schema_str = str(schema)
730
+ assert schema_str.find("(") > 0
731
+ type_variant_op_name = schema_str[: schema_str.find("(")].replace(".", "_")
732
+ op_name = op_name_from_group(g)
733
+ assert type_variant_op_name.startswith(op_name)
734
+
735
+ arg_types = generate_test_ir_arguments(schema)
736
+ arg_declarations = ", ".join(
737
+ (
738
+ arg_name if arg_type is None else f"{arg_name}: {arg_type}"
739
+ for arg_name, arg_type in arg_types
740
+ )
741
+ )
742
+ arg_names = ", ".join((arg_name for arg_name, _ in arg_types))
743
+ assert (
744
+ len(schema.returns) == 1
745
+ and isinstance(schema.returns[0].type, BaseType)
746
+ and schema.returns[0].type.name is BaseTy.Tensor
747
+ )
748
+ test_value_definitions = generate_test_value_definitions(schema, 0)
749
+ test_value_names = generate_test_value_names(schema, 0)
750
+ test_value_definitions2 = generate_test_value_definitions(schema, 1)
751
+ test_value_names2 = generate_test_value_names(schema, 1)
752
+ check_resize = "true" if should_check_resize(schema) else "false"
753
+ generated = f"""
754
+ TEST(StaticRuntime, autogen_{type_variant_op_name}) {{
755
+ const std::string script = R"IR(
756
+ graph({arg_declarations}):
757
+ %bias: None = prim::Constant()
758
+ %ret = aten::{op_name}({arg_names})
759
+ %cloned = aten::clone(%ret, %bias)
760
+ return (%cloned)
761
+ )IR";
762
+
763
+ {test_value_definitions}
764
+ std::vector<IValue> args{{{test_value_names}}};
765
+ testStaticRuntime(script, args, {{}}, /*use_allclose=*/false, /*use_equalnan=*/false, /*check_resize=*/{check_resize});
766
+
767
+ {test_value_definitions2}
768
+ std::vector<IValue> args2{{{test_value_names2}}};
769
+ testStaticRuntime(script, args, args2, /*use_allclose=*/false, /*use_equalnan=*/false, /*check_resize=*/{check_resize});
770
+
771
+ }}
772
+ """
773
+ return generated
774
+
775
+ def view_op_test_case_generator(self, g: NativeFunctionsViewGroup) -> str:
776
+ schema = g.view.func
777
+ schema_str = str(schema)
778
+ assert schema_str.find("(") > 0
779
+ type_variant_op_name = schema_str[: schema_str.find("(")].replace(".", "_")
780
+ op_name = g.view.root_name
781
+ assert type_variant_op_name.startswith(op_name)
782
+
783
+ arg_types = generate_test_ir_arguments(schema)
784
+ arg_declarations = ", ".join(
785
+ (
786
+ arg_name if arg_type is None else f"{arg_name}: {arg_type}"
787
+ for arg_name, arg_type in arg_types
788
+ )
789
+ )
790
+ arg_names = ", ".join((arg_name for arg_name, _ in arg_types))
791
+ assert (
792
+ len(schema.returns) == 1
793
+ and isinstance(schema.returns[0].type, BaseType)
794
+ and schema.returns[0].type.name is BaseTy.Tensor
795
+ )
796
+ test_value_definitions = generate_test_value_definitions(schema, 0)
797
+ test_value_names = generate_test_value_names(schema, 0)
798
+ generated = f"""
799
+ TEST(StaticRuntime, autogen_{type_variant_op_name}) {{
800
+ const std::string script = R"IR(
801
+ graph({arg_declarations}):
802
+ %bias: None = prim::Constant()
803
+ %ret = aten::{op_name}({arg_names})
804
+ %cloned = aten::clone(%ret, %bias)
805
+ return (%cloned)
806
+ )IR";
807
+
808
+ {test_value_definitions}
809
+ std::vector<IValue> args{{{test_value_names}}};
810
+ testStaticRuntime(script, args);
811
+ }}
812
+ """
813
+
814
+ return generated
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torchgen/utils.py ADDED
@@ -0,0 +1,568 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import functools
5
+ import hashlib
6
+ import os
7
+ import re
8
+ import sys
9
+ import textwrap
10
+ from dataclasses import fields, is_dataclass
11
+ from enum import auto, Enum
12
+ from pathlib import Path
13
+ from typing import Any, Callable, Generic, Literal, NoReturn, TYPE_CHECKING, TypeVar
14
+ from typing_extensions import assert_never, deprecated, Self
15
+
16
+ from torchgen.code_template import CodeTemplate
17
+
18
+
19
+ if TYPE_CHECKING:
20
+ from argparse import Namespace
21
+ from collections.abc import Iterable, Iterator, Sequence
22
+
23
+
24
+ TORCHGEN_ROOT = Path(__file__).absolute().parent
25
+ REPO_ROOT = TORCHGEN_ROOT.parent
26
+
27
+
28
+ # Many of these functions share logic for defining both the definition
29
+ # and declaration (for example, the function signature is the same), so
30
+ # we organize them into one function that takes a Target to say which
31
+ # code we want.
32
+ #
33
+ # This is an OPEN enum (we may add more cases to it in the future), so be sure
34
+ # to explicitly specify with Literal[Target.XXX] or Literal[Target.XXX, Target.YYY]
35
+ # what targets are valid for your use.
36
+ class Target(Enum):
37
+ # top level namespace (not including at)
38
+ DEFINITION = auto()
39
+ DECLARATION = auto()
40
+ # TORCH_LIBRARY(...) { ... }
41
+ REGISTRATION = auto()
42
+ # namespace { ... }
43
+ ANONYMOUS_DEFINITION = auto()
44
+ # namespace cpu { ... }
45
+ NAMESPACED_DEFINITION = auto()
46
+ NAMESPACED_DECLARATION = auto()
47
+
48
+
49
+ # Matches "foo" in "foo, bar" but not "foobar". Used to search for the
50
+ # occurrence of a parameter in the derivative formula
51
+ IDENT_REGEX = r"(^|\W){}($|\W)"
52
+
53
+
54
+ # TODO: Use a real parser here; this will get bamboozled
55
+ def split_name_params(schema: str) -> tuple[str, list[str]]:
56
+ m = re.match(r"(\w+)(\.\w+)?\((.*)\)", schema)
57
+ if m is None:
58
+ raise RuntimeError(f"Unsupported function schema: {schema}")
59
+ name, _, params = m.groups()
60
+ return name, params.split(", ")
61
+
62
+
63
+ T = TypeVar("T")
64
+ S = TypeVar("S")
65
+
66
+ # These two functions purposely return generators in analogy to map()
67
+ # so that you don't mix up when you need to list() them
68
+
69
+
70
+ # Map over function that may return None; omit Nones from output sequence
71
+ def mapMaybe(func: Callable[[T], S | None], xs: Iterable[T]) -> Iterator[S]:
72
+ for x in xs:
73
+ r = func(x)
74
+ if r is not None:
75
+ yield r
76
+
77
+
78
+ # Map over function that returns sequences and cat them all together
79
+ def concatMap(func: Callable[[T], Sequence[S]], xs: Iterable[T]) -> Iterator[S]:
80
+ for x in xs:
81
+ yield from func(x)
82
+
83
+
84
+ # Conveniently add error context to exceptions raised. Lets us
85
+ # easily say that an error occurred while processing a specific
86
+ # context.
87
+ @contextlib.contextmanager
88
+ def context(msg_fn: Callable[[], str]) -> Iterator[None]:
89
+ try:
90
+ yield
91
+ except Exception as e:
92
+ # TODO: this does the wrong thing with KeyError
93
+ msg = msg_fn()
94
+ msg = textwrap.indent(msg, " ")
95
+ msg = f"{e.args[0]}\n{msg}" if e.args else msg
96
+ e.args = (msg,) + e.args[1:]
97
+ raise
98
+
99
+
100
+ if TYPE_CHECKING:
101
+ # A little trick from https://github.com/python/mypy/issues/6366
102
+ # for getting mypy to do exhaustiveness checking
103
+ # TODO: put this somewhere else, maybe
104
+ @deprecated("Use typing_extensions.assert_never instead")
105
+ def assert_never(x: NoReturn) -> NoReturn: # type: ignore[misc] # noqa: F811
106
+ raise AssertionError(f"Unhandled type: {type(x).__name__}")
107
+
108
+
109
+ @functools.cache
110
+ def _read_template(template_fn: str) -> CodeTemplate:
111
+ return CodeTemplate.from_file(template_fn)
112
+
113
+
114
+ # String hash that's stable across different executions, unlike builtin hash
115
+ def string_stable_hash(s: str) -> int:
116
+ sha1 = hashlib.sha1(s.encode("latin1"), usedforsecurity=False).digest()
117
+ return int.from_bytes(sha1, byteorder="little")
118
+
119
+
120
+ # A small abstraction for writing out generated files and keeping track
121
+ # of what files have been written (so you can write out a list of output
122
+ # files)
123
+ class FileManager:
124
+ def __init__(
125
+ self,
126
+ install_dir: str | Path,
127
+ template_dir: str | Path,
128
+ dry_run: bool,
129
+ ) -> None:
130
+ self.install_dir = Path(install_dir)
131
+ self.template_dir = Path(template_dir)
132
+ self.files: set[Path] = set()
133
+ self.dry_run = dry_run
134
+
135
+ @property
136
+ def filenames(self) -> frozenset[str]:
137
+ return frozenset({file.as_posix() for file in self.files})
138
+
139
+ def _write_if_changed(self, filename: str | Path, contents: str) -> None:
140
+ file = Path(filename)
141
+ old_contents: str | None = None
142
+ try:
143
+ old_contents = file.read_text(encoding="utf-8")
144
+ except OSError:
145
+ pass
146
+ if contents != old_contents:
147
+ # Create output directory if it doesn't exist
148
+ file.parent.mkdir(parents=True, exist_ok=True)
149
+ file.write_text(contents, encoding="utf-8")
150
+
151
+ # Read from template file and replace pattern with callable (type could be dict or str).
152
+ def substitute_with_template(
153
+ self,
154
+ template_fn: str | Path,
155
+ env_callable: Callable[[], str | dict[str, Any]],
156
+ ) -> str:
157
+ assert not Path(template_fn).is_absolute(), (
158
+ f"template_fn must be relative: {template_fn}"
159
+ )
160
+ template_path = self.template_dir / template_fn
161
+ env = env_callable()
162
+ if isinstance(env, dict):
163
+ if "generated_comment" not in env:
164
+ generator_default = TORCHGEN_ROOT / "gen.py"
165
+ try:
166
+ generator = Path(
167
+ sys.modules["__main__"].__file__ or generator_default
168
+ ).absolute()
169
+ except (KeyError, AttributeError):
170
+ generator = generator_default.absolute()
171
+
172
+ try:
173
+ generator_path = generator.relative_to(REPO_ROOT).as_posix()
174
+ except ValueError:
175
+ generator_path = generator.name
176
+
177
+ env = {
178
+ **env, # copy the original dict instead of mutating it
179
+ "generated_comment": (
180
+ "@" + f"generated by {generator_path} from {template_fn}"
181
+ ),
182
+ }
183
+ template = _read_template(template_path)
184
+ substitute_out = template.substitute(env)
185
+ # Ensure an extra blank line between the class/function definition
186
+ # and the docstring of the previous class/function definition.
187
+ # NB: It is generally not recommended to have docstrings in pyi stub
188
+ # files. But if there are any, we need to ensure that the file
189
+ # is properly formatted.
190
+ return re.sub(
191
+ r'''
192
+ (""")\n+ # match triple quotes
193
+ (
194
+ (\s*@.+\n)* # match decorators if any
195
+ \s*(class|def) # match class/function definition
196
+ )
197
+ ''',
198
+ r"\g<1>\n\n\g<2>",
199
+ substitute_out,
200
+ flags=re.VERBOSE,
201
+ )
202
+ if isinstance(env, str):
203
+ return env
204
+ assert_never(env)
205
+
206
+ def write_with_template(
207
+ self,
208
+ filename: str | Path,
209
+ template_fn: str | Path,
210
+ env_callable: Callable[[], str | dict[str, Any]],
211
+ ) -> None:
212
+ filename = Path(filename)
213
+ assert not filename.is_absolute(), f"filename must be relative: {filename}"
214
+ file = self.install_dir / filename
215
+ assert file not in self.files, f"duplicate file write {file}"
216
+ self.files.add(file)
217
+ if not self.dry_run:
218
+ substitute_out = self.substitute_with_template(
219
+ template_fn=template_fn,
220
+ env_callable=env_callable,
221
+ )
222
+ self._write_if_changed(filename=file, contents=substitute_out)
223
+
224
+ def write(
225
+ self,
226
+ filename: str | Path,
227
+ env_callable: Callable[[], str | dict[str, Any]],
228
+ ) -> None:
229
+ self.write_with_template(filename, filename, env_callable)
230
+
231
+ def write_sharded(
232
+ self,
233
+ filename: str | Path,
234
+ items: Iterable[T],
235
+ *,
236
+ key_fn: Callable[[T], str],
237
+ env_callable: Callable[[T], dict[str, list[str]]],
238
+ num_shards: int,
239
+ base_env: dict[str, Any] | None = None,
240
+ sharded_keys: set[str],
241
+ ) -> None:
242
+ self.write_sharded_with_template(
243
+ filename,
244
+ filename,
245
+ items,
246
+ key_fn=key_fn,
247
+ env_callable=env_callable,
248
+ num_shards=num_shards,
249
+ base_env=base_env,
250
+ sharded_keys=sharded_keys,
251
+ )
252
+
253
+ def write_sharded_with_template(
254
+ self,
255
+ filename: str | Path,
256
+ template_fn: str | Path,
257
+ items: Iterable[T],
258
+ *,
259
+ key_fn: Callable[[T], str],
260
+ env_callable: Callable[[T], dict[str, list[str]]],
261
+ num_shards: int,
262
+ base_env: dict[str, Any] | None = None,
263
+ sharded_keys: set[str],
264
+ ) -> None:
265
+ file = Path(filename)
266
+ assert not file.is_absolute(), f"filename must be relative: {filename}"
267
+ everything: dict[str, Any] = {"shard_id": "Everything"}
268
+ shards: list[dict[str, Any]] = [
269
+ {"shard_id": f"_{i}"} for i in range(num_shards)
270
+ ]
271
+ all_shards = [everything] + shards
272
+
273
+ if base_env is not None:
274
+ for shard in all_shards:
275
+ shard.update(base_env)
276
+
277
+ for key in sharded_keys:
278
+ for shard in all_shards:
279
+ if key in shard:
280
+ assert isinstance(shard[key], list), (
281
+ "sharded keys in base_env must be a list"
282
+ )
283
+ shard[key] = shard[key].copy()
284
+ else:
285
+ shard[key] = []
286
+
287
+ def merge_env(into: dict[str, list[str]], from_: dict[str, list[str]]) -> None:
288
+ for k, v in from_.items():
289
+ assert k in sharded_keys, f"undeclared sharded key {k}"
290
+ into[k] += v
291
+
292
+ if self.dry_run:
293
+ # Dry runs don't write any templates, so incomplete environments are fine
294
+ items = ()
295
+
296
+ for item in items:
297
+ key = key_fn(item)
298
+ sid = string_stable_hash(key) % num_shards
299
+ env = env_callable(item)
300
+
301
+ merge_env(shards[sid], env)
302
+ merge_env(everything, env)
303
+
304
+ for shard in all_shards:
305
+ shard_id = shard["shard_id"]
306
+ self.write_with_template(
307
+ file.with_stem(f"{file.stem}{shard_id}"),
308
+ template_fn,
309
+ lambda: shard,
310
+ )
311
+
312
+ # filenames is used to track compiled files, but FooEverything.cpp isn't meant to be compiled
313
+ self.files.discard(self.install_dir / file.with_stem(f"{file.stem}Everything"))
314
+
315
+ def write_outputs(self, variable_name: str, filename: str | Path) -> None:
316
+ """Write a file containing the list of all outputs which are generated by this script."""
317
+ content = "\n".join(
318
+ (
319
+ "set(",
320
+ variable_name,
321
+ # Use POSIX paths to avoid invalid escape sequences on Windows
322
+ *(f' "{file.as_posix()}"' for file in sorted(self.files)),
323
+ ")",
324
+ )
325
+ )
326
+ self._write_if_changed(filename, content)
327
+
328
+ def template_dir_for_comments(self) -> str:
329
+ """
330
+ This needs to be deterministic. The template dir is an absolute path
331
+ that varies across builds. So, just use the path relative to this file,
332
+ which will point to the codegen source but will be stable.
333
+ """
334
+ return os.path.relpath(self.template_dir, os.path.dirname(__file__))
335
+
336
+
337
+ # Helper function to generate file manager
338
+ def make_file_manager(
339
+ options: Namespace,
340
+ install_dir: str | Path | None = None,
341
+ ) -> FileManager:
342
+ template_dir = os.path.join(options.source_path, "templates")
343
+ install_dir = install_dir if install_dir else options.install_dir
344
+ return FileManager(
345
+ install_dir=install_dir,
346
+ template_dir=template_dir,
347
+ dry_run=options.dry_run,
348
+ )
349
+
350
+
351
+ # Helper function to create a pretty representation for dataclasses
352
+ def dataclass_repr(
353
+ obj: Any,
354
+ indent: int = 0,
355
+ width: int = 80,
356
+ ) -> str:
357
+ # built-in pprint module support dataclasses from python 3.10
358
+ if sys.version_info >= (3, 10):
359
+ from pprint import pformat
360
+
361
+ return pformat(obj, indent, width)
362
+
363
+ return _pformat(obj, indent=indent, width=width)
364
+
365
+
366
+ def _pformat(
367
+ obj: Any,
368
+ indent: int,
369
+ width: int,
370
+ curr_indent: int = 0,
371
+ ) -> str:
372
+ assert is_dataclass(obj), f"obj should be a dataclass, received: {type(obj)}"
373
+
374
+ class_name = obj.__class__.__name__
375
+ # update current indentation level with class name
376
+ curr_indent += len(class_name) + 1
377
+
378
+ fields_list = [(f.name, getattr(obj, f.name)) for f in fields(obj) if f.repr]
379
+
380
+ fields_str = []
381
+ for name, attr in fields_list:
382
+ # update the current indent level with the field name
383
+ # dict, list, set and tuple also add indent as done in pprint
384
+ _curr_indent = curr_indent + len(name) + 1
385
+ if is_dataclass(attr):
386
+ str_repr = _pformat(attr, indent, width, _curr_indent)
387
+ elif isinstance(attr, dict):
388
+ str_repr = _format_dict(attr, indent, width, _curr_indent)
389
+ elif isinstance(attr, (list, set, tuple)):
390
+ str_repr = _format_list(attr, indent, width, _curr_indent)
391
+ else:
392
+ str_repr = repr(attr)
393
+
394
+ fields_str.append(f"{name}={str_repr}")
395
+
396
+ indent_str = curr_indent * " "
397
+ body = f",\n{indent_str}".join(fields_str)
398
+ return f"{class_name}({body})"
399
+
400
+
401
+ def _format_dict(
402
+ attr: dict[Any, Any],
403
+ indent: int,
404
+ width: int,
405
+ curr_indent: int,
406
+ ) -> str:
407
+ curr_indent += indent + 3
408
+ dict_repr = []
409
+ for k, v in attr.items():
410
+ k_repr = repr(k)
411
+ v_str = (
412
+ _pformat(v, indent, width, curr_indent + len(k_repr))
413
+ if is_dataclass(v)
414
+ else repr(v)
415
+ )
416
+ dict_repr.append(f"{k_repr}: {v_str}")
417
+
418
+ return _format(dict_repr, indent, width, curr_indent, "{", "}")
419
+
420
+
421
+ def _format_list(
422
+ attr: list[Any] | set[Any] | tuple[Any, ...],
423
+ indent: int,
424
+ width: int,
425
+ curr_indent: int,
426
+ ) -> str:
427
+ curr_indent += indent + 1
428
+ list_repr = [
429
+ _pformat(l, indent, width, curr_indent) if is_dataclass(l) else repr(l)
430
+ for l in attr
431
+ ]
432
+ start, end = ("[", "]") if isinstance(attr, list) else ("(", ")")
433
+ return _format(list_repr, indent, width, curr_indent, start, end)
434
+
435
+
436
+ def _format(
437
+ fields_str: list[str],
438
+ indent: int,
439
+ width: int,
440
+ curr_indent: int,
441
+ start: str,
442
+ end: str,
443
+ ) -> str:
444
+ delimiter, curr_indent_str = "", ""
445
+ # if it exceed the max width then we place one element per line
446
+ if len(repr(fields_str)) >= width:
447
+ delimiter = "\n"
448
+ curr_indent_str = " " * curr_indent
449
+
450
+ indent_str = " " * indent
451
+ body = f", {delimiter}{curr_indent_str}".join(fields_str)
452
+ return f"{start}{indent_str}{body}{end}"
453
+
454
+
455
+ class NamespaceHelper:
456
+ """A helper for constructing the namespace open and close strings for a nested set of namespaces.
457
+
458
+ e.g. for namespace_str torch::lazy,
459
+
460
+ prologue:
461
+ namespace torch {
462
+ namespace lazy {
463
+
464
+ epilogue:
465
+ } // namespace lazy
466
+ } // namespace torch
467
+ """
468
+
469
+ def __init__(
470
+ self,
471
+ namespace_str: str,
472
+ entity_name: str = "",
473
+ max_level: int = 2,
474
+ ) -> None:
475
+ # cpp_namespace can be a colon joined string such as torch::lazy
476
+ cpp_namespaces = namespace_str.split("::")
477
+ assert len(cpp_namespaces) <= max_level, (
478
+ f"Codegen doesn't support more than {max_level} level(s) of custom namespace. Got {namespace_str}."
479
+ )
480
+ self.cpp_namespace_ = namespace_str
481
+ self.prologue_ = "\n".join([f"namespace {n} {{" for n in cpp_namespaces])
482
+ self.epilogue_ = "\n".join(
483
+ [f"}} // namespace {n}" for n in reversed(cpp_namespaces)]
484
+ )
485
+ self.namespaces_ = cpp_namespaces
486
+ self.entity_name_ = entity_name
487
+
488
+ @staticmethod
489
+ def from_namespaced_entity(
490
+ namespaced_entity: str,
491
+ max_level: int = 2,
492
+ ) -> NamespaceHelper:
493
+ """
494
+ Generate helper from nested namespaces as long as class/function name. E.g.: "torch::lazy::add"
495
+ """
496
+ names = namespaced_entity.split("::")
497
+ entity_name = names[-1]
498
+ namespace_str = "::".join(names[:-1])
499
+ return NamespaceHelper(
500
+ namespace_str=namespace_str, entity_name=entity_name, max_level=max_level
501
+ )
502
+
503
+ @property
504
+ def prologue(self) -> str:
505
+ return self.prologue_
506
+
507
+ @property
508
+ def epilogue(self) -> str:
509
+ return self.epilogue_
510
+
511
+ @property
512
+ def entity_name(self) -> str:
513
+ return self.entity_name_
514
+
515
+ # Only allow certain level of namespaces
516
+ def get_cpp_namespace(self, default: str = "") -> str:
517
+ """
518
+ Return the namespace string from joining all the namespaces by "::" (hence no leading "::").
519
+ Return default if namespace string is empty.
520
+ """
521
+ return self.cpp_namespace_ if self.cpp_namespace_ else default
522
+
523
+
524
+ class OrderedSet(Generic[T]):
525
+ storage: dict[T, Literal[None]]
526
+
527
+ def __init__(self, iterable: Iterable[T] | None = None) -> None:
528
+ if iterable is None:
529
+ self.storage = {}
530
+ else:
531
+ self.storage = dict.fromkeys(iterable)
532
+
533
+ def __contains__(self, item: T) -> bool:
534
+ return item in self.storage
535
+
536
+ def __iter__(self) -> Iterator[T]:
537
+ return iter(self.storage.keys())
538
+
539
+ def update(self, items: OrderedSet[T]) -> None:
540
+ self.storage.update(items.storage)
541
+
542
+ def add(self, item: T) -> None:
543
+ self.storage[item] = None
544
+
545
+ def copy(self) -> OrderedSet[T]:
546
+ ret: OrderedSet[T] = OrderedSet()
547
+ ret.storage = self.storage.copy()
548
+ return ret
549
+
550
+ @staticmethod
551
+ def union(*args: OrderedSet[T]) -> OrderedSet[T]:
552
+ ret = args[0].copy()
553
+ for s in args[1:]:
554
+ ret.update(s)
555
+ return ret
556
+
557
+ def __or__(self, other: OrderedSet[T]) -> OrderedSet[T]:
558
+ return OrderedSet.union(self, other)
559
+
560
+ def __ior__(self, other: OrderedSet[T]) -> Self:
561
+ self.update(other)
562
+ return self
563
+
564
+ def __eq__(self, other: object) -> bool:
565
+ if isinstance(other, OrderedSet):
566
+ return self.storage == other.storage
567
+ else:
568
+ return set(self.storage.keys()) == other
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torchgen/yaml_utils.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Safely load fast C Yaml loader/dumper if they are available
2
+ try:
3
+ from yaml import CSafeLoader as Loader
4
+ except ImportError:
5
+ from yaml import SafeLoader as Loader # type: ignore[assignment, misc]
6
+
7
+ try:
8
+ from yaml import CSafeDumper as Dumper
9
+ except ImportError:
10
+ from yaml import SafeDumper as Dumper # type: ignore[assignment, misc]
11
+ YamlDumper = Dumper
12
+
13
+
14
+ # A custom loader for YAML that errors on duplicate keys.
15
+ # This doesn't happen by default: see https://github.com/yaml/pyyaml/issues/165
16
+ class YamlLoader(Loader):
17
+ def construct_mapping(self, node, deep=False): # type: ignore[no-untyped-def]
18
+ mapping = []
19
+ for key_node, value_node in node.value:
20
+ key = self.construct_object(key_node, deep=deep) # type: ignore[no-untyped-call]
21
+ assert key not in mapping, (
22
+ f"Found a duplicate key in the yaml. key={key}, line={node.start_mark.line}"
23
+ )
24
+ mapping.append(key)
25
+ mapping = super().construct_mapping(node, deep=deep) # type: ignore[no-untyped-call]
26
+ return mapping
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm-4.70.1.dist-info/METADATA ADDED
@@ -0,0 +1,1600 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: tqdm
3
+ Version: 4.70.1
4
+ Summary: Fast, Extensible Progress Meter
5
+ Maintainer-email: tqdm developers <devs@tqdm.ml>
6
+ License: MPL-2.0 AND MIT
7
+ Project-URL: homepage, https://tqdm.github.io
8
+ Project-URL: repository, https://github.com/tqdm/tqdm
9
+ Project-URL: changelog, https://tqdm.github.io/releases
10
+ Project-URL: wiki, https://github.com/tqdm/tqdm/wiki
11
+ Keywords: progressbar,progressmeter,progress,bar,meter,rate,eta,console,terminal,time
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Environment :: Console
14
+ Classifier: Environment :: MacOS X
15
+ Classifier: Environment :: Other Environment
16
+ Classifier: Environment :: Win32 (MS Windows)
17
+ Classifier: Environment :: X11 Applications
18
+ Classifier: Framework :: IPython
19
+ Classifier: Framework :: Jupyter
20
+ Classifier: Intended Audience :: Developers
21
+ Classifier: Intended Audience :: Education
22
+ Classifier: Intended Audience :: End Users/Desktop
23
+ Classifier: Intended Audience :: Other Audience
24
+ Classifier: Intended Audience :: System Administrators
25
+ Classifier: Operating System :: MacOS
26
+ Classifier: Operating System :: MacOS :: MacOS X
27
+ Classifier: Operating System :: Microsoft
28
+ Classifier: Operating System :: Microsoft :: MS-DOS
29
+ Classifier: Operating System :: Microsoft :: Windows
30
+ Classifier: Operating System :: POSIX
31
+ Classifier: Operating System :: POSIX :: BSD
32
+ Classifier: Operating System :: POSIX :: BSD :: FreeBSD
33
+ Classifier: Operating System :: POSIX :: Linux
34
+ Classifier: Operating System :: POSIX :: SunOS/Solaris
35
+ Classifier: Operating System :: Unix
36
+ Classifier: Programming Language :: Python
37
+ Classifier: Programming Language :: Python :: 3
38
+ Classifier: Programming Language :: Python :: 3.8
39
+ Classifier: Programming Language :: Python :: 3.9
40
+ Classifier: Programming Language :: Python :: 3.10
41
+ Classifier: Programming Language :: Python :: 3.11
42
+ Classifier: Programming Language :: Python :: 3.12
43
+ Classifier: Programming Language :: Python :: 3.13
44
+ Classifier: Programming Language :: Python :: 3.14
45
+ Classifier: Programming Language :: Python :: 3 :: Only
46
+ Classifier: Programming Language :: Python :: Implementation
47
+ Classifier: Programming Language :: Python :: Implementation :: IronPython
48
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
49
+ Classifier: Programming Language :: Unix Shell
50
+ Classifier: Topic :: Desktop Environment
51
+ Classifier: Topic :: Education :: Computer Aided Instruction (CAI)
52
+ Classifier: Topic :: Education :: Testing
53
+ Classifier: Topic :: Office/Business
54
+ Classifier: Topic :: Other/Nonlisted Topic
55
+ Classifier: Topic :: Software Development :: Build Tools
56
+ Classifier: Topic :: Software Development :: Libraries
57
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
58
+ Classifier: Topic :: Software Development :: Pre-processors
59
+ Classifier: Topic :: Software Development :: User Interfaces
60
+ Classifier: Topic :: System :: Installation/Setup
61
+ Classifier: Topic :: System :: Logging
62
+ Classifier: Topic :: System :: Monitoring
63
+ Classifier: Topic :: System :: Shells
64
+ Classifier: Topic :: Terminals
65
+ Classifier: Topic :: Utilities
66
+ Requires-Python: >=3.8
67
+ Description-Content-Type: text/x-rst
68
+ License-File: LICENCE
69
+ Requires-Dist: colorama; platform_system == "Windows"
70
+ Provides-Extra: discord
71
+ Requires-Dist: requests; extra == "discord"
72
+ Requires-Dist: envwrap; extra == "discord"
73
+ Provides-Extra: slack
74
+ Requires-Dist: slack-sdk; extra == "slack"
75
+ Requires-Dist: envwrap; extra == "slack"
76
+ Provides-Extra: telegram
77
+ Requires-Dist: requests; extra == "telegram"
78
+ Requires-Dist: envwrap; extra == "telegram"
79
+ Provides-Extra: notebook
80
+ Requires-Dist: ipywidgets>=6; extra == "notebook"
81
+ Dynamic: license-file
82
+
83
+ |Logo|
84
+
85
+ tqdm
86
+ ====
87
+
88
+ |Py-Versions| |Versions| |Conda-Forge-Status| |Docker| |Snapcraft|
89
+
90
+ |Build-Status| |Coverage-Status| |Branch-Coverage-Status| |Codacy-Grade| |Libraries-Rank| |PyPI-Downloads|
91
+
92
+ |LICENCE| |OpenHub-Status| |colab-demo| |binder-demo| |awesome-python|
93
+
94
+ ``tqdm`` derives from the Arabic word *taqaddum* (تقدّم) which can mean "progress,"
95
+ and is an abbreviation for "I love you so much" in Spanish (*te quiero demasiado*).
96
+
97
+ Instantly make your loops show a smart progress meter - just wrap any
98
+ iterable with ``tqdm(iterable)``, and you're done!
99
+
100
+ .. code:: python
101
+
102
+ from tqdm import tqdm
103
+ for i in tqdm(range(10000)):
104
+ ...
105
+
106
+ ``76%|████████████████████████        | 7568/10000 [00:33<00:10, 229.00it/s]``
107
+
108
+ ``trange(N)`` can also be used as a convenient shortcut for
109
+ ``tqdm(range(N))``.
110
+
111
+ |Screenshot|
112
+ |Video| |Slides| |Merch|
113
+
114
+ It can also be executed as a module with pipes:
115
+
116
+ .. code:: sh
117
+
118
+ $ seq 9999999 | tqdm --bytes | wc -l
119
+ 75.2MB [00:00, 217MB/s]
120
+ 9999999
121
+
122
+ $ tar -zcf - docs/ | tqdm --bytes --total `du -sb docs/ | cut -f1` \
123
+ > backup.tgz
124
+ 32%|██████████▍ | 8.89G/27.9G [00:42<01:31, 223MB/s]
125
+
126
+ Overhead is low -- about 60ns per iteration (80ns with ``tqdm.gui``), and is
127
+ unit tested against performance regression.
128
+ By comparison, the well-established
129
+ `ProgressBar <https://github.com/niltonvolpato/python-progressbar>`__ has
130
+ an 800ns/iter overhead.
131
+
132
+ In addition to its low overhead, ``tqdm`` uses smart algorithms to predict
133
+ the remaining time and to skip unnecessary iteration displays, which allows
134
+ for a negligible overhead in most cases.
135
+
136
+ ``tqdm`` works on any platform
137
+ (Linux, Windows, Mac, FreeBSD, NetBSD, Solaris/SunOS),
138
+ in any console or in a GUI, and is also friendly with IPython/Jupyter notebooks.
139
+
140
+ ``tqdm`` does not require any dependencies (not even ``curses``!), just
141
+ Python and an environment supporting ``carriage return \r`` and
142
+ ``line feed \n`` control characters.
143
+
144
+ **Featured Sponsors**
145
+
146
+ ======== ================================================
147
+ |OpenAI| Your Logo Here
148
+ ======== ================================================
149
+ OpenAI `Sponsors <https://github.com/sponsors/tqdm>`__
150
+ ======== ================================================
151
+
152
+ .. |OpenAI| image:: https://avatars.githubusercontent.com/u/14957082?s=96
153
+ :target: https://openai.com
154
+
155
+ ------------------------------------------
156
+
157
+ .. contents:: Table of contents
158
+ :backlinks: top
159
+ :local:
160
+
161
+
162
+ Installation
163
+ ------------
164
+
165
+ Latest PyPI stable release
166
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
167
+
168
+ |Versions| |PyPI-Downloads| |Libraries-Dependents|
169
+
170
+ .. code:: sh
171
+
172
+ pip install tqdm
173
+
174
+ Latest development release on GitHub
175
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
176
+
177
+ |GitHub-Status| |GitHub-Stars| |GitHub-Commits| |GitHub-Forks| |GitHub-Updated|
178
+
179
+ Pull and install pre-release ``devel`` branch:
180
+
181
+ .. code:: sh
182
+
183
+ pip install "git+https://github.com/tqdm/tqdm.git@devel#egg=tqdm"
184
+
185
+ Latest Conda release
186
+ ~~~~~~~~~~~~~~~~~~~~
187
+
188
+ |Conda-Forge-Status|
189
+
190
+ .. code:: sh
191
+
192
+ conda install -c conda-forge tqdm
193
+
194
+ Latest Snapcraft release
195
+ ~~~~~~~~~~~~~~~~~~~~~~~~
196
+
197
+ |Snapcraft|
198
+
199
+ There are 3 channels to choose from:
200
+
201
+ .. code:: sh
202
+
203
+ snap install tqdm # implies --stable, i.e. latest tagged release
204
+ snap install tqdm --candidate # master branch
205
+ snap install tqdm --edge # devel branch
206
+
207
+ Note that ``snap`` binaries are purely for CLI use (not ``import``-able), and
208
+ automatically set up ``bash`` tab-completion.
209
+
210
+ Latest Docker release
211
+ ~~~~~~~~~~~~~~~~~~~~~
212
+
213
+ |Docker|
214
+
215
+ .. code:: sh
216
+
217
+ docker pull tqdm/tqdm
218
+ docker run -i --rm tqdm/tqdm --help
219
+
220
+ Other
221
+ ~~~~~
222
+
223
+ There are other (unofficial) places where ``tqdm`` may be downloaded, particularly for CLI use:
224
+
225
+ |Repology|
226
+
227
+ .. |Repology| image:: https://repology.org/badge/tiny-repos/python:tqdm.svg
228
+ :target: https://repology.org/project/python:tqdm/versions
229
+
230
+ Changelog
231
+ ---------
232
+
233
+ The list of all changes is available either on GitHub's Releases:
234
+ |GitHub-Status|, on the
235
+ `wiki <https://github.com/tqdm/tqdm/wiki/Releases>`__, or on the
236
+ `website <https://tqdm.github.io/releases>`__.
237
+
238
+
239
+ Usage
240
+ -----
241
+
242
+ ``tqdm`` is very versatile and can be used in a number of ways.
243
+ The three main ones are given below.
244
+
245
+ Iterable-based
246
+ ~~~~~~~~~~~~~~
247
+
248
+ Wrap ``tqdm()`` around any iterable:
249
+
250
+ .. code:: python
251
+
252
+ from tqdm import tqdm
253
+ from time import sleep
254
+
255
+ text = ""
256
+ for char in tqdm(["a", "b", "c", "d"]):
257
+ sleep(0.25)
258
+ text = text + char
259
+
260
+ ``trange(i)`` is a special optimised instance of ``tqdm(range(i))``:
261
+
262
+ .. code:: python
263
+
264
+ from tqdm import trange
265
+
266
+ for i in trange(100):
267
+ sleep(0.01)
268
+
269
+ Instantiation outside of the loop allows for manual control over ``tqdm()``:
270
+
271
+ .. code:: python
272
+
273
+ pbar = tqdm(["a", "b", "c", "d"])
274
+ for char in pbar:
275
+ sleep(0.25)
276
+ pbar.set_description("Processing %s" % char)
277
+
278
+ Manual
279
+ ~~~~~~
280
+
281
+ Manual control of ``tqdm()`` updates using a ``with`` statement:
282
+
283
+ .. code:: python
284
+
285
+ with tqdm(total=100) as pbar:
286
+ for i in range(10):
287
+ sleep(0.1)
288
+ pbar.update(10)
289
+
290
+ If the optional variable ``total`` (or an iterable with ``len()``) is
291
+ provided, predictive stats are displayed.
292
+
293
+ ``with`` is also optional (you can just assign ``tqdm()`` to a variable,
294
+ but in this case don't forget to ``del`` or ``close()`` at the end:
295
+
296
+ .. code:: python
297
+
298
+ pbar = tqdm(total=100)
299
+ for i in range(10):
300
+ sleep(0.1)
301
+ pbar.update(10)
302
+ pbar.close()
303
+
304
+ Module
305
+ ~~~~~~
306
+
307
+ Perhaps the most wonderful use of ``tqdm`` is in a script or on the command
308
+ line. Simply inserting ``tqdm`` (or ``python -m tqdm``) between pipes will pass
309
+ through all ``stdin`` to ``stdout`` while printing progress to ``stderr``.
310
+
311
+ The example below demonstrate counting the number of lines in all Python files
312
+ in the current directory, with timing information included.
313
+
314
+ .. code:: sh
315
+
316
+ $ time find . -name '*.py' -type f -exec cat \{} \; | wc -l
317
+ 857365
318
+
319
+ real 0m3.458s
320
+ user 0m0.274s
321
+ sys 0m3.325s
322
+
323
+ $ time find . -name '*.py' -type f -exec cat \{} \; | tqdm | wc -l
324
+ 857366it [00:03, 246471.31it/s]
325
+ 857365
326
+
327
+ real 0m3.585s
328
+ user 0m0.862s
329
+ sys 0m3.358s
330
+
331
+ Note that the usual arguments for ``tqdm`` can also be specified.
332
+
333
+ .. code:: sh
334
+
335
+ $ find . -name '*.py' -type f -exec cat \{} \; |
336
+ tqdm --unit loc --unit_scale --total 857366 >> /dev/null
337
+ 100%|█████████████████████████████████| 857K/857K [00:04<00:00, 246Kloc/s]
338
+
339
+ Backing up a large directory?
340
+
341
+ .. code:: sh
342
+
343
+ $ tar -zcf - docs/ | tqdm --bytes --total `du -sb docs/ | cut -f1` \
344
+ > backup.tgz
345
+ 44%|██████████████▊ | 153M/352M [00:14<00:18, 11.0MB/s]
346
+
347
+ This can be beautified further:
348
+
349
+ .. code:: sh
350
+
351
+ $ BYTES=$(du -sb docs/ | cut -f1)
352
+ $ tar -cf - docs/ \
353
+ | tqdm --bytes --total "$BYTES" --desc Processing | gzip \
354
+ | tqdm --bytes --total "$BYTES" --desc Compressed --position 1 \
355
+ > ~/backup.tgz
356
+ Processing: 100%|██████████████████████| 352M/352M [00:14<00:00, 30.2MB/s]
357
+ Compressed: 42%|█████████▎ | 148M/352M [00:14<00:19, 10.9MB/s]
358
+
359
+ Or done on a file level using 7-zip:
360
+
361
+ .. code:: sh
362
+
363
+ $ 7z a -bd -r backup.7z docs/ | grep Compressing \
364
+ | tqdm --total $(find docs/ -type f | wc -l) --unit files \
365
+ | grep -v Compressing
366
+ 100%|██████████████████████████▉| 15327/15327 [01:00<00:00, 712.96files/s]
367
+
368
+ Pre-existing CLI programs already outputting basic progress information will
369
+ benefit from ``tqdm``'s ``--update`` and ``--update_to`` flags:
370
+
371
+ .. code:: sh
372
+
373
+ $ seq 3 0.1 5 | tqdm --total 5 --update_to --null
374
+ 100%|████████████████████████████████████| 5.0/5 [00:00<00:00, 9673.21it/s]
375
+ $ seq 10 | tqdm --update --null # 1 + 2 + ... + 10 = 55 iterations
376
+ 55it [00:00, 90006.52it/s]
377
+
378
+ FAQ and Known Issues
379
+ --------------------
380
+
381
+ |GitHub-Issues|
382
+
383
+ The most common issues relate to excessive output on multiple lines, instead
384
+ of a neat one-line progress bar.
385
+
386
+ - Consoles in general: require support for carriage return (``CR``, ``\r``).
387
+
388
+ * Some cloud logging consoles which don't support ``\r`` properly
389
+ (`cloudwatch <https://github.com/tqdm/tqdm/issues/966>`__,
390
+ `K8s <https://github.com/tqdm/tqdm/issues/1319>`__) may benefit from
391
+ ``export TQDM_POSITION=-1``.
392
+
393
+ - Nested progress bars:
394
+
395
+ * Consoles in general: require support for moving cursors up to the
396
+ previous line. For example,
397
+ `IDLE <https://github.com/tqdm/tqdm/issues/191#issuecomment-230168030>`__,
398
+ `ConEmu <https://github.com/tqdm/tqdm/issues/254>`__ and
399
+ `PyCharm <https://github.com/tqdm/tqdm/issues/203>`__ (also
400
+ `here <https://github.com/tqdm/tqdm/issues/208>`__,
401
+ `here <https://github.com/tqdm/tqdm/issues/307>`__, and
402
+ `here <https://github.com/tqdm/tqdm/issues/454#issuecomment-335416815>`__)
403
+ lack full support.
404
+ * Windows: additionally may require the Python module ``colorama``
405
+ to ensure nested bars stay within their respective lines.
406
+
407
+ - Unicode:
408
+
409
+ * Environments which report that they support unicode will have solid smooth
410
+ progress bars. The fallback is an ``ascii``-only bar.
411
+ * Windows consoles often only partially support unicode and thus
412
+ `often require explicit ascii=True <https://github.com/tqdm/tqdm/issues/454#issuecomment-335416815>`__
413
+ (also `here <https://github.com/tqdm/tqdm/issues/499>`__). This is due to
414
+ either normal-width unicode characters being incorrectly displayed as
415
+ "wide", or some unicode characters not rendering.
416
+
417
+ - Wrapping generators:
418
+
419
+ * Generator wrapper functions tend to hide the length of iterables.
420
+ ``tqdm`` does not.
421
+ * Replace ``tqdm(enumerate(...))`` with ``enumerate(tqdm(...))`` or
422
+ ``tqdm(enumerate(x), total=len(x), ...)``.
423
+ The same applies to ``numpy.ndenumerate``.
424
+ * Replace ``tqdm(zip(a, b))`` with ``zip(tqdm(a), b)`` or even
425
+ ``zip(tqdm(a), tqdm(b))``.
426
+ * The same applies to ``itertools``.
427
+ * Some useful convenience functions can be found under ``tqdm.contrib``.
428
+
429
+ - `No intermediate output in docker-compose <https://github.com/tqdm/tqdm/issues/771>`__:
430
+ use ``docker-compose run`` instead of ``docker-compose up`` and ``tty: true``.
431
+
432
+ - Overriding defaults via environment variables:
433
+ e.g. in CI/cloud jobs, ``export TQDM_MININTERVAL=5`` to avoid log spam.
434
+ This override logic is handled by the ``tqdm.utils.envwrap`` decorator
435
+ (useful independent of ``tqdm``).
436
+
437
+ If you come across any other difficulties, browse and file |GitHub-Issues|.
438
+
439
+ Documentation
440
+ -------------
441
+
442
+ |Py-Versions| |README-Hits| (Since 19 May 2016)
443
+
444
+ .. code:: python
445
+
446
+ class tqdm():
447
+ """
448
+ Decorate an iterable object, returning an iterator which acts exactly
449
+ like the original iterable, but prints a dynamically updating
450
+ progress bar every time a value is requested.
451
+ """
452
+
453
+ @envwrap("tqdm") # override defaults via env vars
454
+ def __init__(self, iterable=None, desc=None, total=None, leave=True,
455
+ file=None, ncols=None, mininterval=0.1,
456
+ maxinterval=10.0, miniters=None, ascii=None, disable=False,
457
+ unit='it', unit_scale=False, dynamic_ncols=False,
458
+ smoothing=0.3, bar_format=None, initial=0, position=None,
459
+ postfix=None, unit_divisor=1000, write_bytes=False,
460
+ lock_args=None, nrows=None, colour=None, delay=0):
461
+
462
+ Parameters
463
+ ~~~~~~~~~~
464
+
465
+ * iterable : iterable, optional
466
+ Iterable to decorate with a progress bar.
467
+ Leave blank to manually manage the updates.
468
+ * desc : str, optional
469
+ Prefix for the progress bar.
470
+ * total : int or float, optional
471
+ The number of expected iterations. If unspecified,
472
+ len(iterable) is used if possible. If float("inf") or as a last
473
+ resort, only basic progress statistics are displayed
474
+ (no ETA, no progress bar).
475
+ If ``gui`` is True and this parameter needs subsequent updating,
476
+ specify an initial arbitrary large positive number,
477
+ e.g. 9e9.
478
+ * leave : bool, optional
479
+ If [default: True], keeps all traces of the progress bar
480
+ upon termination of iteration.
481
+ If ``None``, will leave only if ``position`` is ``0``.
482
+ * file : ``io.TextIOWrapper`` or ``io.StringIO``, optional
483
+ Specifies where to output the progress messages
484
+ (default: sys.stderr). Uses ``file.write(str)`` and ``file.flush()``
485
+ methods. For encoding, see ``write_bytes``.
486
+ * ncols : int, optional
487
+ The width of the entire output message. If specified,
488
+ dynamically resizes the progress bar to stay within this bound.
489
+ If unspecified, attempts to use environment width. The
490
+ fallback is a meter width of 10 and no limit for the counter and
491
+ statistics. If 0, will not print any meter (only stats).
492
+ * mininterval : float, optional
493
+ Minimum progress display update interval [default: 0.1] seconds.
494
+ * maxinterval : float, optional
495
+ Maximum progress display update interval [default: 10] seconds.
496
+ Automatically adjusts ``miniters`` to correspond to ``mininterval``
497
+ after long display update lag. Only works if ``dynamic_miniters``
498
+ or monitor thread is enabled.
499
+ * miniters : int or float, optional
500
+ Minimum progress display update interval, in iterations.
501
+ If 0 and ``dynamic_miniters``, will automatically adjust to equal
502
+ ``mininterval`` (more CPU efficient, good for tight loops).
503
+ If > 0, will skip display of specified number of iterations.
504
+ Tweak this and ``mininterval`` to get very efficient loops.
505
+ If your progress is erratic with both fast and slow iterations
506
+ (network, skipping items, etc) you should set miniters=1.
507
+ * ascii : bool or str, optional
508
+ If unspecified or False, use unicode (smooth blocks) to fill
509
+ the meter. The fallback is to use ASCII characters " 123456789#".
510
+ * disable : bool, optional
511
+ Whether to disable the entire progress bar wrapper
512
+ [default: False]. If set to None, disable on non-TTY.
513
+ * unit : str, optional
514
+ String that will be used to define the unit of each iteration
515
+ [default: it].
516
+ * unit_scale : bool or int or float, optional
517
+ If 1 or True, the number of iterations will be reduced/scaled
518
+ automatically and a metric prefix following the
519
+ International System of Units standard will be added
520
+ (kilo, mega, etc.) [default: False]. If any other non-zero
521
+ number, will scale ``total`` and ``n``.
522
+ * dynamic_ncols : bool, optional
523
+ If set, constantly alters ``ncols`` and ``nrows`` to the
524
+ environment (allowing for window resizes) [default: False].
525
+ * smoothing : float, optional
526
+ Exponential moving average smoothing factor for speed estimates
527
+ (ignored in GUI mode). Ranges from 0 (average speed) to 1
528
+ (current/instantaneous speed) [default: 0.3].
529
+ * bar_format : str, optional
530
+ Specify a custom bar string formatting. May impact performance.
531
+ [default: '{l_bar}{bar}{r_bar}'], where
532
+ l_bar='{desc}: {percentage:3.0f}%|' and
533
+ r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, '
534
+ '{rate_fmt}{postfix}]'
535
+ Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,
536
+ percentage, elapsed, elapsed_s, ncols, nrows, desc, unit,
537
+ rate, rate_fmt, rate_noinv, rate_noinv_fmt,
538
+ rate_inv, rate_inv_fmt, postfix, unit_divisor,
539
+ remaining, remaining_s, eta.
540
+ Note that a trailing ": " is automatically removed after {desc}
541
+ if the latter is empty.
542
+ * initial : int or float, optional
543
+ The initial counter value. Useful when restarting a progress
544
+ bar [default: 0]. If using float, consider specifying ``{n:.3f}``
545
+ or similar in ``bar_format``, or specifying ``unit_scale``.
546
+ * position : int, optional
547
+ Specify the line offset to print this bar (starting from 0)
548
+ Automatic if unspecified.
549
+ Useful to manage multiple bars at once (eg, from threads).
550
+ * postfix : dict or ``*``, optional
551
+ Specify additional stats to display at the end of the bar.
552
+ Calls ``set_postfix(**postfix)`` if possible (dict).
553
+ * unit_divisor : float, optional
554
+ [default: 1000], ignored unless ``unit_scale`` is True.
555
+ * write_bytes : bool, optional
556
+ Whether to write bytes. If (default: False) will write unicode.
557
+ * lock_args : tuple, optional
558
+ Passed to ``refresh`` for intermediate output
559
+ (initialisation, iterating, and updating).
560
+ * nrows : int, optional
561
+ The screen height. If specified, hides nested bars outside this
562
+ bound. If unspecified, attempts to use environment height.
563
+ The fallback is 20.
564
+ * colour : str, optional
565
+ Bar colour (e.g. 'green', '#00ff00').
566
+ * delay : float, optional
567
+ Don't display until [default: 0] seconds have elapsed.
568
+
569
+ Extra CLI Options
570
+ ~~~~~~~~~~~~~~~~~
571
+
572
+ * delim : chr, optional
573
+ Delimiting character [default: '\n']. Use '\0' for null.
574
+ N.B.: on Windows systems, Python converts '\n' to '\r\n'.
575
+ * buf_size : int, optional
576
+ String buffer size in bytes [default: 256]
577
+ used when ``delim`` is specified.
578
+ * bytes : bool, optional
579
+ If true, will count bytes, ignore ``delim``, and default
580
+ ``unit_scale`` to True, ``unit_divisor`` to 1024, and ``unit`` to 'B'.
581
+ * tee : bool, optional
582
+ If true, passes ``stdin`` to both ``stderr`` and ``stdout``.
583
+ * update : bool, optional
584
+ If true, will treat input as newly elapsed iterations,
585
+ i.e. numbers to pass to ``update()``. Note that this is slow
586
+ (~2e5 it/s) since every input must be decoded as a number.
587
+ * update_to : bool, optional
588
+ If true, will treat input as total elapsed iterations,
589
+ i.e. numbers to assign to ``self.n``. Note that this is slow
590
+ (~2e5 it/s) since every input must be decoded as a number.
591
+ * null : bool, optional
592
+ If true, will discard input (no stdout).
593
+ * manpath : str, optional
594
+ Directory in which to install tqdm man pages.
595
+ * comppath : str, optional
596
+ Directory in which to place tqdm completion.
597
+ * log : str, optional
598
+ CRITICAL|FATAL|ERROR|WARN(ING)|[default: 'INFO']|DEBUG|NOTSET.
599
+
600
+ Returns
601
+ ~~~~~~~
602
+
603
+ * out : decorated iterator.
604
+
605
+ .. code:: python
606
+
607
+ class tqdm():
608
+ def update(self, n=1):
609
+ """
610
+ Manually update the progress bar, useful for streams
611
+ such as reading files.
612
+ E.g.:
613
+ >>> t = tqdm(total=filesize) # Initialise
614
+ >>> for current_buffer in stream:
615
+ ... ...
616
+ ... t.update(len(current_buffer))
617
+ >>> t.close()
618
+ The last line is highly recommended, but possibly not necessary if
619
+ `t.update()` will be called in such a way that `filesize` will be
620
+ exactly reached and printed.
621
+
622
+ Parameters
623
+ ----------
624
+ n : int or float, optional
625
+ Increment to add to the internal counter of iterations
626
+ [default: 1]. If using float, consider specifying `{n:.3f}`
627
+ or similar in `bar_format`, or specifying `unit_scale`.
628
+
629
+ Returns
630
+ -------
631
+ out : bool or None
632
+ True if a `display()` was triggered.
633
+ """
634
+
635
+ def close(self):
636
+ """Cleanup and (if leave=False) close the progress bar."""
637
+
638
+ def clear(self, nomove=False):
639
+ """Clear current bar display."""
640
+
641
+ def refresh(self):
642
+ """
643
+ Force refresh the display of this bar.
644
+
645
+ Parameters
646
+ ----------
647
+ nolock : bool, optional
648
+ If `True`, does not lock.
649
+ If [default: `False`]: calls `acquire()` on internal lock.
650
+ lock_args : tuple, optional
651
+ Passed to internal lock's `acquire()`.
652
+ If specified, will only `display()` if `acquire()` returns `True`.
653
+ """
654
+
655
+ def unpause(self):
656
+ """Restart tqdm timer from last print time."""
657
+
658
+ def reset(self, total=None):
659
+ """
660
+ Resets to 0 iterations for repeated use.
661
+
662
+ Consider combining with `leave=True`.
663
+
664
+ Parameters
665
+ ----------
666
+ total : int or float, optional. Total to use for the new bar.
667
+ """
668
+
669
+ def set_description(self, desc=None, refresh=True):
670
+ """
671
+ Set/modify description of the progress bar.
672
+
673
+ Parameters
674
+ ----------
675
+ desc : str, optional
676
+ refresh : bool, optional
677
+ Forces refresh [default: True].
678
+ """
679
+
680
+ def set_postfix(self, ordered_dict=None, refresh=True, **tqdm_kwargs):
681
+ """
682
+ Set/modify postfix (additional stats)
683
+ with automatic formatting based on datatype.
684
+
685
+ Parameters
686
+ ----------
687
+ ordered_dict : dict or OrderedDict, optional
688
+ refresh : bool, optional
689
+ Forces refresh [default: True].
690
+ kwargs : dict, optional
691
+ """
692
+
693
+ @classmethod
694
+ def write(cls, s, file=sys.stdout, end="\n"):
695
+ """Print a message via tqdm (without overlap with bars)."""
696
+
697
+ @property
698
+ def format_dict(self):
699
+ """Public API for read-only member access."""
700
+
701
+ def display(self, msg=None, pos=None):
702
+ """
703
+ Use `self.sp` to display `msg` in the specified `pos`.
704
+
705
+ Consider overloading this function when inheriting to use e.g.:
706
+ `self.some_frontend(**self.format_dict)` instead of `self.sp`.
707
+
708
+ Parameters
709
+ ----------
710
+ msg : str, optional. What to display (default: `repr(self)`).
711
+ pos : int, optional. Position to `moveto`
712
+ (default: `abs(self.pos)`).
713
+ """
714
+
715
+ @classmethod
716
+ @contextmanager
717
+ def wrapattr(cls, stream, method, total=None, bytes=True, **tqdm_kwargs):
718
+ """
719
+ stream : file-like object.
720
+ method : str, "read" or "write". The result of `read()` and
721
+ the first argument of `write()` should have a `len()`.
722
+
723
+ >>> with tqdm.wrapattr(file_obj, "read", total=file_obj.size) as fobj:
724
+ ... while True:
725
+ ... chunk = fobj.read(chunk_size)
726
+ ... if not chunk:
727
+ ... break
728
+ """
729
+
730
+ @classmethod
731
+ def pandas(cls, *targs, **tqdm_kwargs):
732
+ """Registers the current `tqdm` class with `pandas`."""
733
+
734
+ def trange(*args, **tqdm_kwargs):
735
+ """Shortcut for `tqdm(range(*args), **tqdm_kwargs)`."""
736
+
737
+ Convenience Functions
738
+ ~~~~~~~~~~~~~~~~~~~~~
739
+
740
+ .. code:: python
741
+
742
+ def tqdm.contrib.tenumerate(iterable, start=0, total=None,
743
+ tqdm_class=tqdm.auto.tqdm, **tqdm_kwargs):
744
+ """Equivalent of `numpy.ndenumerate` or builtin `enumerate`."""
745
+
746
+ def tqdm.contrib.tzip(iter1, *iter2plus, **tqdm_kwargs):
747
+ """Equivalent of builtin `zip`."""
748
+
749
+ def tqdm.contrib.tmap(function, *sequences, **tqdm_kwargs):
750
+ """Equivalent of builtin `map`."""
751
+
752
+ Submodules
753
+ ~~~~~~~~~~
754
+
755
+ .. code:: python
756
+
757
+ class tqdm.notebook.tqdm(tqdm.tqdm):
758
+ """IPython/Jupyter Notebook widget."""
759
+
760
+ class tqdm.auto.tqdm(tqdm.tqdm):
761
+ """Automatically chooses between `tqdm.notebook` and `tqdm.tqdm`."""
762
+
763
+ class tqdm.asyncio.tqdm(tqdm.tqdm):
764
+ """Asynchronous version."""
765
+ @classmethod
766
+ def as_completed(cls, fs, *, loop=None, timeout=None, total=None,
767
+ **tqdm_kwargs):
768
+ """Wrapper for `asyncio.as_completed`."""
769
+
770
+ class tqdm.gui.tqdm(tqdm.tqdm):
771
+ """Matplotlib GUI version."""
772
+
773
+ class tqdm.tk.tqdm(tqdm.tqdm):
774
+ """Tkinter GUI version."""
775
+
776
+ class tqdm.rich.tqdm(tqdm.tqdm):
777
+ """`rich.progress` version."""
778
+
779
+ class tqdm.keras.TqdmCallback(keras.callbacks.Callback):
780
+ """Keras callback for epoch and batch progress."""
781
+
782
+ class tqdm.dask.TqdmCallback(dask.callbacks.Callback):
783
+ """Dask callback for task progress."""
784
+
785
+
786
+ ``contrib``
787
+ +++++++++++
788
+
789
+ The ``tqdm.contrib`` package also contains experimental modules:
790
+
791
+ - `tqdm.contrib.itertools <https://tqdm.github.io/docs/contrib.itertools/>`_: Thin wrappers around ``itertools``
792
+ - `tqdm.contrib.concurrent <https://tqdm.github.io/docs/contrib.concurrent/>`_: Thin wrappers around ``concurrent.futures``
793
+ - `tqdm.contrib.slack <https://tqdm.github.io/docs/contrib.slack/>`_: Posts to `Slack <https://slack.com>`__ bots
794
+ - `tqdm.contrib.discord <https://tqdm.github.io/docs/contrib.discord/>`_: Posts to `Discord <https://discord.com>`__ bots
795
+ - `tqdm.contrib.telegram <https://tqdm.github.io/docs/contrib.telegram/>`_: Posts to `Telegram <https://telegram.org>`__ bots
796
+ - `tqdm.contrib.bells <https://tqdm.github.io/docs/shortcuts/>`_: Automagically enables all optional features
797
+
798
+ * ``auto``, ``pandas``, ``slack``, ``discord``, ``telegram``
799
+
800
+ .. image:: https://tqdm.github.io/img/screenshot-discord.png
801
+ :alt: Screenshot of `tqdm.contrib.discord` in action
802
+
803
+ Examples and Advanced Usage
804
+ ---------------------------
805
+
806
+ - See the `examples <https://github.com/tqdm/tqdm/tree/master/examples>`__
807
+ folder;
808
+ - import the module and run ``help()``;
809
+ - consult the `wiki <https://github.com/tqdm/tqdm/wiki>`__;
810
+
811
+ * this has an
812
+ `excellent article <https://github.com/tqdm/tqdm/wiki/How-to-make-a-great-Progress-Bar>`__
813
+ on how to make a **great** progress bar;
814
+
815
+ - check out the `slides from PyData London <https://tqdm.github.io/PyData2019/slides.html>`__, or
816
+ - run the |binder-demo|.
817
+
818
+ Description and additional stats
819
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
820
+
821
+ Custom information can be displayed and updated dynamically on ``tqdm`` bars
822
+ with the ``desc`` and ``postfix`` arguments:
823
+
824
+ .. code:: python
825
+
826
+ from tqdm import tqdm, trange
827
+ from random import random, randint
828
+ from time import sleep
829
+
830
+ with trange(10) as t:
831
+ for i in t:
832
+ # Description will be displayed on the left
833
+ t.set_description('GEN %i' % i)
834
+ # Postfix will be displayed on the right,
835
+ # formatted automatically based on argument's datatype
836
+ t.set_postfix(loss=random(), gen=randint(1,999), str='h',
837
+ lst=[1, 2])
838
+ sleep(0.1)
839
+
840
+ with tqdm(total=10, bar_format="{postfix[0]} {postfix[1][value]:>8.2g}",
841
+ postfix=["Batch", {"value": 0}]) as t:
842
+ for i in range(10):
843
+ sleep(0.1)
844
+ t.postfix[1]["value"] = i / 2
845
+ t.update()
846
+
847
+ Points to remember when using ``{postfix[...]}`` in the ``bar_format`` string:
848
+
849
+ - ``postfix`` also needs to be passed as an initial argument in a compatible
850
+ format, and
851
+ - ``postfix`` will be auto-converted to a string if it is a ``dict``-like
852
+ object. To prevent this behaviour, insert an extra item into the dictionary
853
+ where the key is not a string.
854
+
855
+ Additional ``bar_format`` parameters may also be defined by overriding
856
+ ``format_dict``, and the bar itself may be modified using ``ascii``:
857
+
858
+ .. code:: python
859
+
860
+ from tqdm import tqdm
861
+ class TqdmExtraFormat(tqdm):
862
+ """Provides a `total_time` format parameter"""
863
+ @property
864
+ def format_dict(self):
865
+ d = super().format_dict
866
+ total_time = d["elapsed"] * (d["total"] or 0) / max(d["n"], 1)
867
+ d.update(total_time=self.format_interval(total_time) + " in total")
868
+ return d
869
+
870
+ for i in TqdmExtraFormat(
871
+ range(9), ascii=" .oO0",
872
+ bar_format="{total_time}: {percentage:.0f}%|{bar}{r_bar}"):
873
+ if i == 4:
874
+ break
875
+
876
+ .. code::
877
+
878
+ 00:00 in total: 44%|0000. | 4/9 [00:00<00:00, 962.93it/s]
879
+
880
+ Note that ``{bar}`` also supports a format specifier ``[width][type]``.
881
+
882
+ - ``width``
883
+
884
+ * unspecified (default): automatic to fill ``ncols``
885
+ * ``int >= 0``: fixed width overriding ``ncols`` logic
886
+ * ``int < 0``: subtract from the automatic default
887
+
888
+ - ``type``
889
+
890
+ * ``a``: ascii (``ascii=True`` override)
891
+ * ``u``: unicode (``ascii=False`` override)
892
+ * ``b``: blank (``ascii=" "`` override)
893
+
894
+ This means a fixed bar with right-justified text may be created by using:
895
+ ``bar_format="{l_bar}{bar:10}|{bar:-10b}right-justified"``
896
+
897
+ Nested progress bars
898
+ ~~~~~~~~~~~~~~~~~~~~
899
+
900
+ ``tqdm`` supports nested progress bars. Here's an example:
901
+
902
+ .. code:: python
903
+
904
+ from tqdm.auto import trange
905
+ from time import sleep
906
+
907
+ for i in trange(4, desc='1st loop'):
908
+ for j in trange(5, desc='2nd loop'):
909
+ for k in trange(50, desc='3rd loop', leave=False):
910
+ sleep(0.01)
911
+
912
+ For manual control over positioning (e.g. for multi-processing use),
913
+ you may specify ``position=n`` where ``n=0`` for the outermost bar,
914
+ ``n=1`` for the next, and so on.
915
+ However, it's best to check if ``tqdm`` can work without manual ``position``
916
+ first.
917
+
918
+ .. code:: python
919
+
920
+ from time import sleep
921
+ from tqdm import trange, tqdm
922
+ from multiprocessing import Pool, RLock, freeze_support
923
+
924
+ L = list(range(9))
925
+
926
+ def progresser(n):
927
+ interval = 0.001 / (n + 2)
928
+ total = 5000
929
+ text = f"#{n}, est. {interval * total:<04.2}s"
930
+ for _ in trange(total, desc=text, position=n):
931
+ sleep(interval)
932
+
933
+ if __name__ == '__main__':
934
+ freeze_support() # for Windows support
935
+ tqdm.set_lock(RLock()) # for managing output contention
936
+ p = Pool(initializer=tqdm.set_lock, initargs=(tqdm.get_lock(),))
937
+ p.map(progresser, L)
938
+
939
+ Note that in Python 3, ``tqdm.write`` is thread-safe:
940
+
941
+ .. code:: python
942
+
943
+ from time import sleep
944
+ from tqdm import tqdm, trange
945
+ from concurrent.futures import ThreadPoolExecutor
946
+
947
+ L = list(range(9))
948
+
949
+ def progresser(n):
950
+ interval = 0.001 / (n + 2)
951
+ total = 5000
952
+ text = f"#{n}, est. {interval * total:<04.2}s"
953
+ for _ in trange(total, desc=text):
954
+ sleep(interval)
955
+ if n == 6:
956
+ tqdm.write("n == 6 completed.")
957
+ tqdm.write("`tqdm.write()` is thread-safe in py3!")
958
+
959
+ if __name__ == '__main__':
960
+ with ThreadPoolExecutor() as p:
961
+ p.map(progresser, L)
962
+
963
+ Hooks and callbacks
964
+ ~~~~~~~~~~~~~~~~~~~
965
+
966
+ ``tqdm`` can easily support callbacks/hooks and manual updates.
967
+ Here's an example with ``urllib``:
968
+
969
+ **``urllib.urlretrieve`` documentation**
970
+
971
+ | [...]
972
+ | If present, the hook function will be called once
973
+ | on establishment of the network connection and once after each block read
974
+ | thereafter. The hook will be passed three arguments; a count of blocks
975
+ | transferred so far, a block size in bytes, and the total size of the file.
976
+ | [...]
977
+
978
+ .. code:: python
979
+
980
+ import urllib, os
981
+ from tqdm import tqdm
982
+ urllib = getattr(urllib, 'request', urllib)
983
+
984
+ class TqdmUpTo(tqdm):
985
+ """Provides `update_to(n)` which uses `tqdm.update(delta_n)`."""
986
+ def update_to(self, b=1, bsize=1, tsize=None):
987
+ """
988
+ b : int, optional
989
+ Number of blocks transferred so far [default: 1].
990
+ bsize : int, optional
991
+ Size of each block (in tqdm units) [default: 1].
992
+ tsize : int, optional
993
+ Total size (in tqdm units). If [default: None] remains unchanged.
994
+ """
995
+ if tsize is not None:
996
+ self.total = tsize
997
+ return self.update(b * bsize - self.n) # also sets self.n = b * bsize
998
+
999
+ eg_link = "https://cgi.cdcl.ml/matryoshka.zip"
1000
+ with TqdmUpTo(unit='B', unit_scale=True, unit_divisor=1024, miniters=1,
1001
+ desc=eg_link.split('/')[-1]) as t: # all optional kwargs
1002
+ urllib.urlretrieve(eg_link, filename=os.devnull,
1003
+ reporthook=t.update_to, data=None)
1004
+ t.total = t.n
1005
+
1006
+ Inspired by `twine#242 <https://github.com/pypa/twine/pull/242>`__.
1007
+ Functional alternative in
1008
+ `examples/tqdm_wget.py <https://github.com/tqdm/tqdm/blob/master/examples/tqdm_wget.py>`__.
1009
+
1010
+ It is recommend to use ``miniters=1`` whenever there is potentially
1011
+ large differences in iteration speed (e.g. downloading a file over
1012
+ a patchy connection).
1013
+
1014
+ **Wrapping read/write methods**
1015
+
1016
+ To measure throughput through a file-like object's ``read`` or ``write``
1017
+ methods, use ``CallbackIOWrapper``:
1018
+
1019
+ .. code:: python
1020
+
1021
+ from tqdm.auto import tqdm
1022
+ from tqdm.utils import CallbackIOWrapper
1023
+
1024
+ with tqdm(total=file_obj.size,
1025
+ unit='B', unit_scale=True, unit_divisor=1024) as t:
1026
+ fobj = CallbackIOWrapper(t.update, file_obj, "read")
1027
+ while True:
1028
+ chunk = fobj.read(chunk_size)
1029
+ if not chunk:
1030
+ break
1031
+ t.reset()
1032
+ # ... continue to use `t` for something else
1033
+
1034
+ Alternatively, use the even simpler ``wrapattr`` convenience function,
1035
+ which would condense both the ``urllib`` and ``CallbackIOWrapper`` examples
1036
+ down to:
1037
+
1038
+ .. code:: python
1039
+
1040
+ import urllib, os
1041
+ from tqdm import tqdm
1042
+
1043
+ eg_link = "https://cgi.cdcl.ml/matryoshka.zip"
1044
+ response = getattr(urllib, 'request', urllib).urlopen(eg_link)
1045
+ with tqdm.wrapattr(open(os.devnull, "wb"), "write",
1046
+ miniters=1, desc=eg_link.split('/')[-1],
1047
+ total=getattr(response, 'length', None)) as fout:
1048
+ for chunk in response:
1049
+ fout.write(chunk)
1050
+
1051
+ The ``requests`` equivalent is nearly identical:
1052
+
1053
+ .. code:: python
1054
+
1055
+ import requests, os
1056
+ from tqdm import tqdm
1057
+
1058
+ eg_link = "https://cgi.cdcl.ml/matryoshka.zip"
1059
+ response = requests.get(eg_link, stream=True)
1060
+ with tqdm.wrapattr(open(os.devnull, "wb"), "write",
1061
+ miniters=1, desc=eg_link.split('/')[-1],
1062
+ total=int(response.headers.get('content-length', 0))) as fout:
1063
+ for chunk in response.iter_content(chunk_size=4096):
1064
+ fout.write(chunk)
1065
+
1066
+ **Custom callback**
1067
+
1068
+ ``tqdm`` is known for intelligently skipping unnecessary displays. To make a
1069
+ custom callback take advantage of this, simply use the return value of
1070
+ ``update()``. This is set to ``True`` if a ``display()`` was triggered.
1071
+
1072
+ .. code:: python
1073
+
1074
+ from tqdm.auto import tqdm as std_tqdm
1075
+
1076
+ def external_callback(*args, **kwargs):
1077
+ ...
1078
+
1079
+ class TqdmExt(std_tqdm):
1080
+ def update(self, n=1):
1081
+ displayed = super().update(n)
1082
+ if displayed:
1083
+ external_callback(**self.format_dict)
1084
+ return displayed
1085
+
1086
+ ``asyncio``
1087
+ ~~~~~~~~~~~
1088
+
1089
+ Note that ``break`` isn't currently caught by asynchronous iterators.
1090
+ This means that ``tqdm`` cannot clean up after itself in this case:
1091
+
1092
+ .. code:: python
1093
+
1094
+ from tqdm.asyncio import tqdm
1095
+
1096
+ async for i in tqdm(range(9)):
1097
+ if i == 2:
1098
+ break
1099
+
1100
+ Instead, either call ``pbar.close()`` manually or use the context manager syntax:
1101
+
1102
+ .. code:: python
1103
+
1104
+ from tqdm.asyncio import tqdm
1105
+
1106
+ with tqdm(range(9)) as pbar:
1107
+ async for i in pbar:
1108
+ if i == 2:
1109
+ break
1110
+
1111
+ Pandas Integration
1112
+ ~~~~~~~~~~~~~~~~~~
1113
+
1114
+ Due to popular demand we've added support for ``pandas`` -- here's an example
1115
+ for ``DataFrame.progress_apply`` and ``DataFrameGroupBy.progress_apply``:
1116
+
1117
+ .. code:: python
1118
+
1119
+ import pandas as pd
1120
+ import numpy as np
1121
+ from tqdm import tqdm
1122
+
1123
+ df = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))
1124
+
1125
+ # Register `pandas.progress_apply` and `pandas.Series.map_apply` with `tqdm`
1126
+ # (can use `tqdm.gui.tqdm`, `tqdm.notebook.tqdm`, optional kwargs, etc.)
1127
+ tqdm.pandas(desc="my bar!")
1128
+
1129
+ # Now you can use `progress_apply` instead of `apply`
1130
+ # and `progress_map` instead of `map`
1131
+ df.progress_apply(lambda x: x**2)
1132
+ # can also groupby:
1133
+ # df.groupby(0).progress_apply(lambda x: x**2)
1134
+
1135
+ In case you're interested in how this works (and how to modify it for your
1136
+ own callbacks), see the
1137
+ `examples <https://github.com/tqdm/tqdm/tree/master/examples>`__
1138
+ folder or import the module and run ``help()``.
1139
+
1140
+ Keras Integration
1141
+ ~~~~~~~~~~~~~~~~~
1142
+
1143
+ A ``keras`` callback is also available:
1144
+
1145
+ .. code:: python
1146
+
1147
+ from tqdm.keras import TqdmCallback
1148
+
1149
+ ...
1150
+
1151
+ model.fit(..., verbose=0, callbacks=[TqdmCallback()])
1152
+
1153
+ Dask Integration
1154
+ ~~~~~~~~~~~~~~~~
1155
+
1156
+ A ``dask`` callback is also available:
1157
+
1158
+ .. code:: python
1159
+
1160
+ from tqdm.dask import TqdmCallback
1161
+
1162
+ with TqdmCallback(desc="compute"):
1163
+ ...
1164
+ arr.compute()
1165
+
1166
+ # or use callback globally
1167
+ cb = TqdmCallback(desc="global")
1168
+ cb.register()
1169
+ arr.compute()
1170
+
1171
+ IPython/Jupyter Integration
1172
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1173
+
1174
+ IPython/Jupyter is supported via the ``tqdm.notebook`` submodule:
1175
+
1176
+ .. code:: python
1177
+
1178
+ from tqdm.notebook import trange, tqdm
1179
+ from time import sleep
1180
+
1181
+ for i in trange(3, desc='1st loop'):
1182
+ for j in tqdm(range(100), desc='2nd loop'):
1183
+ sleep(0.01)
1184
+
1185
+ In addition to ``tqdm`` features, the submodule provides a native Jupyter
1186
+ widget (compatible with IPython v1-v4 and Jupyter), fully working nested bars
1187
+ and colour hints (blue: normal, green: completed, red: error/interrupt,
1188
+ light blue: no ETA); as demonstrated below.
1189
+
1190
+ |Screenshot-Jupyter1|
1191
+ |Screenshot-Jupyter2|
1192
+ |Screenshot-Jupyter3|
1193
+
1194
+ The ``notebook`` version supports percentage or pixels for overall width
1195
+ (e.g.: ``ncols='100%'`` or ``ncols='480px'``).
1196
+
1197
+ It is also possible to let ``tqdm`` automatically choose between
1198
+ console or notebook versions by using the ``autonotebook`` submodule:
1199
+
1200
+ .. code:: python
1201
+
1202
+ from tqdm.autonotebook import tqdm
1203
+ tqdm.pandas()
1204
+
1205
+ Note that this will issue a ``TqdmExperimentalWarning`` if run in a notebook
1206
+ since it is not meant to be possible to distinguish between ``jupyter notebook``
1207
+ and ``jupyter console``. Use ``auto`` instead of ``autonotebook`` to suppress
1208
+ this warning.
1209
+
1210
+ Note that notebooks will display the bar in the cell where it was created.
1211
+ This may be a different cell from the one where it is used.
1212
+ If this is not desired, either
1213
+
1214
+ - delay the creation of the bar to the cell where it must be displayed, or
1215
+ - create the bar with ``display=False``, and in a later cell call
1216
+ ``display(bar.container)``:
1217
+
1218
+ .. code:: python
1219
+
1220
+ from tqdm.notebook import tqdm
1221
+ pbar = tqdm(..., display=False)
1222
+
1223
+ .. code:: python
1224
+
1225
+ # different cell
1226
+ display(pbar.container)
1227
+
1228
+ The ``keras`` callback has a ``display()`` method which can be used likewise:
1229
+
1230
+ .. code:: python
1231
+
1232
+ from tqdm.keras import TqdmCallback
1233
+ cbk = TqdmCallback(display=False)
1234
+
1235
+ .. code:: python
1236
+
1237
+ # different cell
1238
+ cbk.display()
1239
+ model.fit(..., verbose=0, callbacks=[cbk])
1240
+
1241
+ Another possibility is to have a single bar (near the top of the notebook)
1242
+ which is constantly re-used (using ``reset()`` rather than ``close()``).
1243
+ For this reason, the notebook version (unlike the CLI version) does not
1244
+ automatically call ``close()`` upon ``Exception``.
1245
+
1246
+ .. code:: python
1247
+
1248
+ from tqdm.notebook import tqdm
1249
+ pbar = tqdm()
1250
+
1251
+ .. code:: python
1252
+
1253
+ # different cell
1254
+ iterable = range(100)
1255
+ pbar.reset(total=len(iterable)) # initialise with new `total`
1256
+ for i in iterable:
1257
+ pbar.update()
1258
+ pbar.refresh() # force print final status but don't `close()`
1259
+
1260
+ Custom Integration
1261
+ ~~~~~~~~~~~~~~~~~~
1262
+
1263
+ To change the default arguments (such as making ``dynamic_ncols=True``),
1264
+ simply use built-in Python magic:
1265
+
1266
+ .. code:: python
1267
+
1268
+ from functools import partial
1269
+ from tqdm import tqdm as std_tqdm
1270
+ tqdm = partial(std_tqdm, dynamic_ncols=True)
1271
+
1272
+ For further customisation,
1273
+ ``tqdm`` may be inherited from to create custom callbacks (as with the
1274
+ ``TqdmUpTo`` example `above <#hooks-and-callbacks>`__) or for custom frontends
1275
+ (e.g. GUIs such as notebook or plotting packages). In the latter case:
1276
+
1277
+ 1. ``def __init__()`` to call ``super().__init__(..., gui=True)`` to disable
1278
+ terminal ``status_printer`` creation.
1279
+ 2. Redefine: ``close()``, ``clear()``, ``display()``.
1280
+
1281
+ Consider overloading ``display()`` to use e.g.
1282
+ ``self.frontend(**self.format_dict)`` instead of ``self.sp(repr(self))``.
1283
+
1284
+ Some submodule examples of inheritance:
1285
+
1286
+ - `tqdm/notebook.py <https://github.com/tqdm/tqdm/blob/master/tqdm/notebook.py>`__
1287
+ - `tqdm/gui.py <https://github.com/tqdm/tqdm/blob/master/tqdm/gui.py>`__
1288
+ - `tqdm/tk.py <https://github.com/tqdm/tqdm/blob/master/tqdm/tk.py>`__
1289
+ - `tqdm/contrib/slack.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/slack.py>`__
1290
+ - `tqdm/contrib/discord.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/discord.py>`__
1291
+ - `tqdm/contrib/telegram.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/telegram.py>`__
1292
+
1293
+ Dynamic Monitor/Meter
1294
+ ~~~~~~~~~~~~~~~~~~~~~
1295
+
1296
+ You can use a ``tqdm`` as a meter which is not monotonically increasing.
1297
+ This could be because ``n`` decreases (e.g. a CPU usage monitor) or ``total``
1298
+ changes.
1299
+
1300
+ One example would be recursively searching for files. The ``total`` is the
1301
+ number of objects found so far, while ``n`` is the number of those objects which
1302
+ are files (rather than folders):
1303
+
1304
+ .. code:: python
1305
+
1306
+ from tqdm import tqdm
1307
+ import os.path
1308
+
1309
+ def find_files_recursively(path, show_progress=True):
1310
+ files = []
1311
+ # total=1 assumes `path` is a file
1312
+ t = tqdm(total=1, unit="file", disable=not show_progress)
1313
+ if not os.path.exists(path):
1314
+ raise IOError("Cannot find:" + path)
1315
+
1316
+ def append_found_file(f):
1317
+ files.append(f)
1318
+ t.update()
1319
+
1320
+ def list_found_dir(path):
1321
+ """returns os.listdir(path) assuming os.path.isdir(path)"""
1322
+ listing = os.listdir(path)
1323
+ # subtract 1 since a "file" we found was actually this directory
1324
+ t.total += len(listing) - 1
1325
+ # fancy way to give info without forcing a refresh
1326
+ t.set_postfix(dir=path[-10:], refresh=False)
1327
+ t.update(0) # may trigger a refresh
1328
+ return listing
1329
+
1330
+ def recursively_search(path):
1331
+ if os.path.isdir(path):
1332
+ for f in list_found_dir(path):
1333
+ recursively_search(os.path.join(path, f))
1334
+ else:
1335
+ append_found_file(path)
1336
+
1337
+ recursively_search(path)
1338
+ t.set_postfix(dir=path)
1339
+ t.close()
1340
+ return files
1341
+
1342
+ Using ``update(0)`` is a handy way to let ``tqdm`` decide when to trigger a
1343
+ display refresh to avoid console spamming.
1344
+
1345
+ Writing messages
1346
+ ~~~~~~~~~~~~~~~~
1347
+
1348
+ This is a work in progress (see
1349
+ `#737 <https://github.com/tqdm/tqdm/issues/737>`__).
1350
+
1351
+ Since ``tqdm`` uses a simple printing mechanism to display progress bars,
1352
+ you should not write any message in the terminal using ``print()`` while
1353
+ a progress bar is open.
1354
+
1355
+ To write messages in the terminal without any collision with ``tqdm`` bar
1356
+ display, a ``.write()`` method is provided:
1357
+
1358
+ .. code:: python
1359
+
1360
+ from tqdm.auto import tqdm, trange
1361
+ from time import sleep
1362
+
1363
+ bar = trange(10)
1364
+ for i in bar:
1365
+ # Print using tqdm class method .write()
1366
+ sleep(0.1)
1367
+ if not (i % 3):
1368
+ tqdm.write("Done task %i" % i)
1369
+ # Can also use bar.write()
1370
+
1371
+ By default, this will print to standard output ``sys.stdout``. but you can
1372
+ specify any file-like object using the ``file`` argument. For example, this
1373
+ can be used to redirect the messages writing to a log file or class.
1374
+
1375
+ Redirecting writing
1376
+ ~~~~~~~~~~~~~~~~~~~
1377
+
1378
+ If using a library that can print messages to the console, editing the library
1379
+ by replacing ``print()`` with ``tqdm.write()`` may not be desirable.
1380
+ In that case, redirecting ``sys.stdout`` to ``tqdm.write()`` is an option.
1381
+
1382
+ To redirect ``sys.stdout``, create a file-like class that will write
1383
+ any input string to ``tqdm.write()``, and supply the arguments
1384
+ ``file=sys.stdout, dynamic_ncols=True``.
1385
+
1386
+ A reusable canonical example is given below:
1387
+
1388
+ .. code:: python
1389
+
1390
+ from time import sleep
1391
+ import contextlib
1392
+ import sys
1393
+ from tqdm import tqdm
1394
+ from tqdm.contrib import DummyTqdmFile
1395
+
1396
+
1397
+ @contextlib.contextmanager
1398
+ def std_out_err_redirect_tqdm():
1399
+ orig_out_err = sys.stdout, sys.stderr
1400
+ try:
1401
+ sys.stdout, sys.stderr = map(DummyTqdmFile, orig_out_err)
1402
+ yield orig_out_err[0]
1403
+ # Relay exceptions
1404
+ except Exception as exc:
1405
+ raise exc
1406
+ # Always restore sys.stdout/err if necessary
1407
+ finally:
1408
+ sys.stdout, sys.stderr = orig_out_err
1409
+
1410
+ def some_fun(i):
1411
+ print("Fee, fi, fo,".split()[i])
1412
+
1413
+ # Redirect stdout to tqdm.write() (don't forget the `as save_stdout`)
1414
+ with std_out_err_redirect_tqdm() as orig_stdout:
1415
+ # tqdm needs the original stdout
1416
+ # and dynamic_ncols=True to autodetect console width
1417
+ for i in tqdm(range(3), file=orig_stdout, dynamic_ncols=True):
1418
+ sleep(.5)
1419
+ some_fun(i)
1420
+
1421
+ # After the `with`, printing is restored
1422
+ print("Done!")
1423
+
1424
+ Redirecting ``logging``
1425
+ ~~~~~~~~~~~~~~~~~~~~~~~
1426
+
1427
+ Similar to ``sys.stdout``/``sys.stderr`` as detailed above, console ``logging``
1428
+ may also be redirected to ``tqdm.write()``.
1429
+
1430
+ Warning: if also redirecting ``sys.stdout``/``sys.stderr``, make sure to
1431
+ redirect ``logging`` first if needed.
1432
+
1433
+ Helper methods are available in ``tqdm.contrib.logging``. For example:
1434
+
1435
+ .. code:: python
1436
+
1437
+ import logging
1438
+ from tqdm import trange
1439
+ from tqdm.contrib.logging import logging_redirect_tqdm
1440
+
1441
+ LOG = logging.getLogger(__name__)
1442
+
1443
+ if __name__ == '__main__':
1444
+ logging.basicConfig(level=logging.INFO)
1445
+ with logging_redirect_tqdm():
1446
+ for i in trange(9):
1447
+ if i == 4:
1448
+ LOG.info("console logging redirected to `tqdm.write()`")
1449
+ # logging restored
1450
+
1451
+ Monitoring thread, intervals and miniters
1452
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1453
+
1454
+ ``tqdm`` implements a few tricks to increase efficiency and reduce overhead.
1455
+
1456
+ - Avoid unnecessary frequent bar refreshing: ``mininterval`` defines how long
1457
+ to wait between each refresh. ``tqdm`` always gets updated in the background,
1458
+ but it will display only every ``mininterval``.
1459
+ - Reduce number of calls to check system clock/time.
1460
+ - ``mininterval`` is more intuitive to configure than ``miniters``.
1461
+ A clever adjustment system ``dynamic_miniters`` will automatically adjust
1462
+ ``miniters`` to the amount of iterations that fit into time ``mininterval``.
1463
+ Essentially, ``tqdm`` will check if it's time to print without actually
1464
+ checking time. This behaviour can be still be bypassed by manually setting
1465
+ ``miniters``.
1466
+
1467
+ However, consider a case with a combination of fast and slow iterations.
1468
+ After a few fast iterations, ``dynamic_miniters`` will set ``miniters`` to a
1469
+ large number. When iteration rate subsequently slows, ``miniters`` will
1470
+ remain large and thus reduce display update frequency. To address this:
1471
+
1472
+ - ``maxinterval`` defines the maximum time between display refreshes.
1473
+ A concurrent monitoring thread checks for overdue updates and forces one
1474
+ where necessary.
1475
+
1476
+ The monitoring thread should not have a noticeable overhead, and guarantees
1477
+ updates at least every 10 seconds by default.
1478
+ This value can be directly changed by setting the ``monitor_interval`` of
1479
+ any ``tqdm`` instance (i.e. ``t = tqdm.tqdm(...); t.monitor_interval = 2``).
1480
+ The monitor thread may be disabled application-wide by setting
1481
+ ``tqdm.tqdm.monitor_interval = 0`` before instantiation of any ``tqdm`` bar.
1482
+
1483
+
1484
+ Merch
1485
+ -----
1486
+
1487
+ You can buy `tqdm branded merch <https://tqdm.github.io/merch>`__ now!
1488
+
1489
+ Contributions
1490
+ -------------
1491
+
1492
+ |GitHub-Commits| |GitHub-Issues| |GitHub-PRs| |OpenHub-Status| |GitHub-Contributions| |CII Best Practices|
1493
+
1494
+ All source code is hosted on `GitHub <https://github.com/tqdm/tqdm>`__.
1495
+ Contributions are welcome.
1496
+
1497
+ See the
1498
+ `CONTRIBUTING <https://github.com/tqdm/tqdm/blob/master/CONTRIBUTING.md>`__
1499
+ file for more information.
1500
+
1501
+ Developers who have contributed more that 5 *loc* (surviving lines of code):
1502
+
1503
+ |git-fame|
1504
+
1505
+ Honourable mentions:
1506
+
1507
+ - Casper da Costa-Luis `casperdcl <https://github.com/casperdcl>`__ primary maintainer |Gift-Casper|
1508
+ - Stephen Larroque `lrq3000 <https://github.com/lrq3000>`__ maintainer
1509
+ - Hadrien Mary `hadim <https://github.com/hadim>`__ maintainer
1510
+ - Mikhail Korobov `kmike <https://github.com/kmike>`__ maintainer
1511
+ - Noam Yorav-Raphael `noamraph <https://github.com/noamraph>`__ original author
1512
+
1513
+ Ports to Other Languages
1514
+ ~~~~~~~~~~~~~~~~~~~~~~~~
1515
+
1516
+ A list is available on
1517
+ `this wiki page <https://github.com/tqdm/tqdm/wiki/tqdm-ports>`__.
1518
+
1519
+
1520
+ LICENCE
1521
+ -------
1522
+
1523
+ Open Source (OSI approved): |LICENCE|
1524
+
1525
+ Citation information: |DOI|
1526
+
1527
+ |README-Hits| (Since 19 May 2016)
1528
+
1529
+ .. |Logo| image:: https://tqdm.github.io/img/logo.gif
1530
+ .. |Screenshot| image:: https://tqdm.github.io/img/tqdm.gif
1531
+ .. |Video| image:: https://tqdm.github.io/img/video.jpg
1532
+ :target: https://tqdm.github.io/video
1533
+ .. |Slides| image:: https://tqdm.github.io/img/slides.jpg
1534
+ :target: https://tqdm.github.io/PyData2019/slides.html
1535
+ .. |Merch| image:: https://tqdm.github.io/img/merch.jpg
1536
+ :target: https://tqdm.github.io/merch
1537
+ .. |Build-Status| image:: https://img.shields.io/github/actions/workflow/status/tqdm/tqdm/test.yml?branch=master&label=tqdm&logo=GitHub
1538
+ :target: https://github.com/tqdm/tqdm/actions/workflows/test.yml
1539
+ .. |Coverage-Status| image:: https://img.shields.io/coveralls/github/tqdm/tqdm/master?logo=coveralls
1540
+ :target: https://coveralls.io/github/tqdm/tqdm
1541
+ .. |Branch-Coverage-Status| image:: https://codecov.io/gh/tqdm/tqdm/branch/master/graph/badge.svg
1542
+ :target: https://codecov.io/gh/tqdm/tqdm
1543
+ .. |Codacy-Grade| image:: https://app.codacy.com/project/badge/Grade/3f965571598f44549c7818f29cdcf177
1544
+ :target: https://app.codacy.com/gh/tqdm/tqdm/dashboard
1545
+ .. |CII Best Practices| image:: https://bestpractices.coreinfrastructure.org/projects/3264/badge
1546
+ :target: https://bestpractices.coreinfrastructure.org/projects/3264
1547
+ .. |GitHub-Status| image:: https://img.shields.io/github/tag/tqdm/tqdm.svg?maxAge=86400&logo=github&logoColor=white
1548
+ :target: https://github.com/tqdm/tqdm/releases
1549
+ .. |GitHub-Forks| image:: https://img.shields.io/github/forks/tqdm/tqdm.svg?logo=github&logoColor=white
1550
+ :target: https://github.com/tqdm/tqdm/network
1551
+ .. |GitHub-Stars| image:: https://img.shields.io/github/stars/tqdm/tqdm.svg?logo=github&logoColor=white
1552
+ :target: https://github.com/tqdm/tqdm/stargazers
1553
+ .. |GitHub-Commits| image:: https://img.shields.io/github/commit-activity/y/tqdm/tqdm.svg?logo=git&logoColor=white
1554
+ :target: https://github.com/tqdm/tqdm/graphs/commit-activity
1555
+ .. |GitHub-Issues| image:: https://img.shields.io/github/issues-closed/tqdm/tqdm.svg?logo=github&logoColor=white
1556
+ :target: https://github.com/tqdm/tqdm/issues?q=
1557
+ .. |GitHub-PRs| image:: https://img.shields.io/github/issues-pr-closed/tqdm/tqdm.svg?logo=github&logoColor=white
1558
+ :target: https://github.com/tqdm/tqdm/pulls
1559
+ .. |GitHub-Contributions| image:: https://img.shields.io/github/contributors/tqdm/tqdm.svg?logo=github&logoColor=white
1560
+ :target: https://github.com/tqdm/tqdm/graphs/contributors
1561
+ .. |GitHub-Updated| image:: https://img.shields.io/github/last-commit/tqdm/tqdm/master.svg?logo=github&logoColor=white&label=pushed
1562
+ :target: https://github.com/tqdm/tqdm/pulse
1563
+ .. |git-fame| image:: https://git-fame.cdcl.ml/gh/tqdm/tqdm?min=5&w=1&M=1&C=1&excl=(png|gif|jpg)$&enum=1&auth=share
1564
+ :alt: git-fame.cdcl.ml/gh/tqdm/tqdm
1565
+ :target: https://git-fame.cdcl.ml/gh/tqdm/tqdm?w=1&M=1&C=1&excl=(png|gif|jpg)$&enum=1&auth=share
1566
+ .. |Gift-Casper| image:: https://img.shields.io/badge/sponsor-casper-ff69b4.svg
1567
+ :target: https://cdcl.ml/sponsor
1568
+ .. |Versions| image:: https://img.shields.io/pypi/v/tqdm.svg
1569
+ :target: https://tqdm.github.io/releases
1570
+ .. |PyPI-Downloads| image:: https://static.pepy.tech/personalized-badge/tqdm?left_text=downloads%2Fmonth
1571
+ :target: https://pepy.tech/project/tqdm
1572
+ .. |Py-Versions| image:: https://img.shields.io/pypi/pyversions/tqdm.svg?logo=python&logoColor=white
1573
+ :target: https://pypi.org/project/tqdm
1574
+ .. |Conda-Forge-Status| image:: https://img.shields.io/conda/v/conda-forge/tqdm.svg?label=conda-forge&logo=conda-forge
1575
+ :target: https://anaconda.org/conda-forge/tqdm
1576
+ .. |Snapcraft| image:: https://img.shields.io/badge/snap-install-82BEA0.svg?logo=snapcraft
1577
+ :target: https://snapcraft.io/tqdm
1578
+ .. |Docker| image:: https://img.shields.io/badge/docker-pull-blue.svg?logo=docker&logoColor=white
1579
+ :target: https://hub.docker.com/r/tqdm/tqdm
1580
+ .. |Libraries-Rank| image:: https://img.shields.io/librariesio/sourcerank/pypi/tqdm.svg?logo=koding&logoColor=white
1581
+ :target: https://libraries.io/pypi/tqdm
1582
+ .. |Libraries-Dependents| image:: https://img.shields.io/librariesio/dependent-repos/pypi/tqdm.svg?logo=koding&logoColor=white
1583
+ :target: https://github.com/tqdm/tqdm/network/dependents
1584
+ .. |OpenHub-Status| image:: https://www.openhub.net/p/tqdm/widgets/project_thin_badge?format=gif
1585
+ :target: https://www.openhub.net/p/tqdm?ref=Thin+badge
1586
+ .. |awesome-python| image:: https://awesome.re/mentioned-badge.svg
1587
+ :target: https://github.com/vinta/awesome-python
1588
+ .. |LICENCE| image:: https://img.shields.io/pypi/l/tqdm.svg
1589
+ :target: https://raw.githubusercontent.com/tqdm/tqdm/master/LICENCE
1590
+ .. |DOI| image:: https://img.shields.io/badge/DOI-10.5281/zenodo.595120-blue.svg
1591
+ :target: https://doi.org/10.5281/zenodo.595120
1592
+ .. |colab-demo| image:: https://colab.research.google.com/assets/colab-badge.svg
1593
+ :target: https://colab.research.google.com/github/tqdm/tqdm/blob/master/DEMO.ipynb
1594
+ .. |binder-demo| image:: https://mybinder.org/badge_logo.svg
1595
+ :target: https://mybinder.org/v2/gh/tqdm/tqdm/master?filepath=DEMO.ipynb
1596
+ .. |Screenshot-Jupyter1| image:: https://tqdm.github.io/img/jupyter-1.gif
1597
+ .. |Screenshot-Jupyter2| image:: https://tqdm.github.io/img/jupyter-2.gif
1598
+ .. |Screenshot-Jupyter3| image:: https://tqdm.github.io/img/jupyter-3.gif
1599
+ .. |README-Hits| image:: https://cgi.cdcl.ml/hits?q=tqdm&style=social&r=https://github.com/tqdm/tqdm&l=https://tqdm.github.io/img/favicon.png&f=https://tqdm.github.io/img/logo.gif
1600
+ :target: https://cgi.cdcl.ml/hits?q=tqdm&a=plot&r=https://github.com/tqdm/tqdm&l=https://tqdm.github.io/img/favicon.png&f=https://tqdm.github.io/img/logo.gif&style=social
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm-4.70.1.dist-info/RECORD ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ../../../bin/tqdm,sha256=qSyz2bGDEZTbvAQbUcUsEsyONTfYepUj1nLRkI5X3dc,317
2
+ tqdm-4.70.1.dist-info/METADATA,sha256=pdpwuWav6jp1lxYEG61xh_Ls4CwiNIz558ClErvxX1c,57366
3
+ tqdm-4.70.1.dist-info/RECORD,,
4
+ tqdm-4.70.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
5
+ tqdm-4.70.1.dist-info/entry_points.txt,sha256=ReJCH7Ui3Zyh6M16E4OhsZ1oU7WtMXCfbtoyBhGO29Y,39
6
+ tqdm-4.70.1.dist-info/licenses/LICENCE,sha256=_P-Hw6R86AKKhRKqGC1PzwrRyQVE7nXPmzQ2hMrBlN4,1985
7
+ tqdm-4.70.1.dist-info/top_level.txt,sha256=NLiUJNfmc9At15s7JURiwvqMEjUi9G5PMGRrmMYzNSM,5
8
+ tqdm/__init__.py,sha256=9mQNYSSqP99JasubEC1POJLMmhkkBH6cJZxPIR5G2pQ,1572
9
+ tqdm/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30
10
+ tqdm/_main.py,sha256=9ySvgmi_2Sw4CAo5UDW0Q2dxfTryboEWGHohfCJz0sA,283
11
+ tqdm/_monitor.py,sha256=1VcavuotYSN6K-1jbpNuy6HYtr3mwo5Nh_jZMQ-jg3A,4013
12
+ tqdm/_tqdm.py,sha256=LfLCuJ6bpsVo9xilmtBXyEm1vGnUCFrliW85j3J-nD4,283
13
+ tqdm/_tqdm_gui.py,sha256=03Hc8KayxJveieI5-0-2NGiDpLvw9jZekofJUV7CCwk,287
14
+ tqdm/_tqdm_notebook.py,sha256=BuHiLuxu6uEfZFaPJW3RPpPaxaVctEQA3kdSJSDL1hw,307
15
+ tqdm/_tqdm_pandas.py,sha256=c9jptUgigN6axRDhRd4Rif98Tmxeopc1nFNFhIpbFUE,888
16
+ tqdm/_utils.py,sha256=CfLztxFY-QRiNfxQCqAb2N8E13uauIM95RSQiFlaEuE,559
17
+ tqdm/asyncio.py,sha256=IpcGo6ZFwc6KKHYj5s7h4kaRiogcabJ6PcqHj6jdy0I,3196
18
+ tqdm/auto.py,sha256=nDZflj6p2zKkjBCNBourrhS81zYfZy1_dQvbckrdW8o,871
19
+ tqdm/autonotebook.py,sha256=2pNgGCJDsesNNyYnmSve8BNQLiGSgo97SsPoMXCrNRQ,1440
20
+ tqdm/cli.py,sha256=t1j_PqI0SuMyhJGoBxMPCXY-UTbfjciaAQYxAU_f_V0,11011
21
+ tqdm/completion.sh,sha256=j79KbSmpIj_E11jfTfBXrGnUTzKXVpQ1vGVQvsyDRl4,946
22
+ tqdm/contrib/__init__.py,sha256=1GMYYE866WCvlHg5MdmzOvPsQj4ZuMlXzz8xcRcJD60,2479
23
+ tqdm/contrib/bells.py,sha256=IaxC2YW57xHDinxdUDQHvSego0HSTdDTExQQENvSB_k,921
24
+ tqdm/contrib/concurrent.py,sha256=CpxrwcKaQRH7nwTPG3mVYuleGs_u0MNhW4hTuabpYYs,9873
25
+ tqdm/contrib/discord.py,sha256=LPjxDbmfiYtw3OAm_WhtwbX9BVYDlPc8lJ96aY3YZDE,5337
26
+ tqdm/contrib/itertools.py,sha256=MA9-Jvb3ToseppInvev2iF4bokN7GQy4Q4LgjUyYdA4,2949
27
+ tqdm/contrib/logging.py,sha256=0nFn2C7qUUiKPB19qTGuS9Lfja8aiFW0u9kybRdG0hU,3902
28
+ tqdm/contrib/slack.py,sha256=sC182v7xBkfGftnDeUmQALMOfwQzU3ZiNf1Q_XA1DjI,4049
29
+ tqdm/contrib/telegram.py,sha256=ybTraGjUQx5m443TsX6pJ7Uxrpsh1m4a43BTWVl_4e4,5081
30
+ tqdm/contrib/utils_worker.py,sha256=vaxyJyagYwOCQXLUMd86bCbI4sPqZysuMGbDSGmvEWo,1199
31
+ tqdm/dask.py,sha256=9Ei58eVqTossRLhAfWyUFCduXYKjmLmwkaXIy-CHYfs,1319
32
+ tqdm/gui.py,sha256=maQ7jgB5leWHwxMlbBv08hpe5lytvmH0hEARu22GRdU,5481
33
+ tqdm/keras.py,sha256=ugd80-xCxMqnrbx_DEOpmj6c2Sh1xoVtQ8V9-bw29eo,4396
34
+ tqdm/notebook.py,sha256=6xkUTcYRsFxN4_BSUYYZ51kAgI7ycnT0HLpP9HukEqg,10888
35
+ tqdm/rich.py,sha256=J04yq6y2Ur9012zC7PkczA1t7cDjet88hmBkrAv-s2s,5255
36
+ tqdm/std.py,sha256=3XbZZd5SxZCBnew3ZkQiDLNdxIMeQO-0wwlEiE_FfYY,58047
37
+ tqdm/tk.py,sha256=3VsB1MDAkCItaWu7CmMb2CoTLMiqmDiEgNi3yiqQ5GY,6702
38
+ tqdm/tqdm.1,sha256=MLg9qjeHThZpPEQbWVrf5P5gOXMKHE_X606FSOBI9eU,7538
39
+ tqdm/utils.py,sha256=o_f0V32H_wrn0XmRno3j9pJ9xlp5xL0fHT3gtqL-k58,9746
40
+ tqdm/version.py,sha256=0uH4TLe8I8H71x29dlmtEZBObLT3b5IW-nytF3V0IVw,233
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm-4.70.1.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm-4.70.1.dist-info/entry_points.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [console_scripts]
2
+ tqdm = tqdm.cli:main
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm-4.70.1.dist-info/licenses/LICENCE ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ `tqdm` is a product of collaborative work.
2
+ Unless otherwise stated, all authors (see commit logs) retain copyright
3
+ for their respective work, and release the work under the MIT licence
4
+ (text below).
5
+
6
+ Exceptions or notable authors are listed below
7
+ in reverse chronological order:
8
+
9
+ * files: *
10
+ MPL-2.0 2015-2026 (c) Casper da Costa-Luis
11
+ [casperdcl](https://github.com/casperdcl).
12
+ * files: tqdm/_tqdm.py
13
+ MIT 2016 (c) [PR #96] on behalf of Google Inc.
14
+ * files: tqdm/_tqdm.py README.rst .gitignore
15
+ MIT 2013 (c) Noam Yorav-Raphael, original author.
16
+
17
+ [PR #96]: https://github.com/tqdm/tqdm/pull/96
18
+
19
+
20
+ Mozilla Public Licence (MPL) v. 2.0 - Exhibit A
21
+ -----------------------------------------------
22
+
23
+ This Source Code Form is subject to the terms of the
24
+ Mozilla Public License, v. 2.0.
25
+ If a copy of the MPL was not distributed with this project,
26
+ You can obtain one at https://mozilla.org/MPL/2.0/.
27
+
28
+
29
+ MIT License (MIT)
30
+ -----------------
31
+
32
+ Copyright (c) 2013 noamraph
33
+
34
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
35
+ this software and associated documentation files (the "Software"), to deal in
36
+ the Software without restriction, including without limitation the rights to
37
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
38
+ the Software, and to permit persons to whom the Software is furnished to do so,
39
+ subject to the following conditions:
40
+
41
+ The above copyright notice and this permission notice shall be included in all
42
+ copies or substantial portions of the Software.
43
+
44
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
45
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
46
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
47
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
48
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
49
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm-4.70.1.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ tqdm
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/__init__.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ._monitor import TMonitor, TqdmSynchronisationWarning
2
+ from ._tqdm_pandas import tqdm_pandas
3
+ from .cli import main # TODO: remove in v5.0.0
4
+ from .gui import tqdm as tqdm_gui # TODO: remove in v5.0.0
5
+ from .gui import trange as tgrange # TODO: remove in v5.0.0
6
+ from .std import (
7
+ TqdmDeprecationWarning, TqdmExperimentalWarning, TqdmKeyError, TqdmMonitorWarning,
8
+ TqdmTypeError, TqdmWarning, tqdm, trange)
9
+ from .version import __version__
10
+
11
+ __all__ = ['tqdm', 'tqdm_gui', 'trange', 'tgrange', 'tqdm_pandas',
12
+ 'tqdm_notebook', 'tnrange', 'main', 'TMonitor',
13
+ 'TqdmTypeError', 'TqdmKeyError',
14
+ 'TqdmWarning', 'TqdmDeprecationWarning',
15
+ 'TqdmExperimentalWarning',
16
+ 'TqdmMonitorWarning', 'TqdmSynchronisationWarning',
17
+ '__version__']
18
+
19
+
20
+ def tqdm_notebook(*args, **kwargs): # pragma: no cover
21
+ """See tqdm.notebook.tqdm for full documentation"""
22
+ from warnings import warn
23
+
24
+ from .notebook import tqdm as _tqdm_notebook
25
+ warn("This function will be removed in tqdm==5.0.0\n"
26
+ "Please use `tqdm.notebook.tqdm` instead of `tqdm.tqdm_notebook`",
27
+ TqdmDeprecationWarning, stacklevel=2)
28
+ return _tqdm_notebook(*args, **kwargs)
29
+
30
+
31
+ def tnrange(*args, **kwargs): # pragma: no cover
32
+ """Shortcut for `tqdm.notebook.tqdm(range(*args), **kwargs)`."""
33
+ from warnings import warn
34
+
35
+ from .notebook import trange as _tnrange
36
+ warn("Please use `tqdm.notebook.trange` instead of `tqdm.tnrange`",
37
+ TqdmDeprecationWarning, stacklevel=2)
38
+ return _tnrange(*args, **kwargs)
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/__main__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .cli import main
2
+
3
+ main()
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (2.02 kB). View file
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/__pycache__/_monitor.cpython-311.pyc ADDED
Binary file (5.27 kB). View file
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/__pycache__/_tqdm_pandas.cpython-311.pyc ADDED
Binary file (1.57 kB). View file
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/__pycache__/cli.cpython-311.pyc ADDED
Binary file (18.2 kB). View file
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/__pycache__/gui.cpython-311.pyc ADDED
Binary file (8.59 kB). View file
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/__pycache__/std.cpython-311.pyc ADDED
Binary file (71.8 kB). View file
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/__pycache__/utils.cpython-311.pyc ADDED
Binary file (19.3 kB). View file
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/__pycache__/version.cpython-311.pyc ADDED
Binary file (522 Bytes). View file
 
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/_main.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from warnings import warn
2
+
3
+ from .cli import * # NOQA
4
+ from .cli import __all__ # NOQA
5
+ from .std import TqdmDeprecationWarning
6
+
7
+ warn("This function will be removed in tqdm==5.0.0\n"
8
+ "Please use `tqdm.cli.*` instead of `tqdm._main.*`",
9
+ TqdmDeprecationWarning, stacklevel=2)
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/_monitor.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import atexit
2
+ from threading import Event, Thread, current_thread
3
+ from time import time
4
+ from warnings import warn
5
+
6
+ __all__ = ["TMonitor", "TqdmSynchronisationWarning"]
7
+
8
+
9
+ class TqdmSynchronisationWarning(RuntimeWarning):
10
+ """
11
+ tqdm multi-thread/-process errors which may cause incorrect nesting
12
+ but otherwise no adverse effects
13
+ """
14
+
15
+
16
+ class TMonitor(Thread):
17
+ """
18
+ Monitoring thread for tqdm bars.
19
+ Monitors if tqdm bars are taking too much time to display
20
+ and readjusts miniters automatically if necessary.
21
+
22
+ Parameters
23
+ ----------
24
+ tqdm_cls : class
25
+ tqdm class to use (can be core tqdm or a submodule).
26
+ sleep_interval : float
27
+ Time to sleep between monitoring checks.
28
+ """
29
+ _test = {} # internal vars for unit testing
30
+
31
+ def __init__(self, tqdm_cls, sleep_interval):
32
+ Thread.__init__(self, name="tqdm_monitor")
33
+ self.daemon = True # kill thread when main killed (KeyboardInterrupt)
34
+ self.woken = 0 # last time woken up, to sync with monitor
35
+ self.tqdm_cls = tqdm_cls
36
+ self.sleep_interval = sleep_interval
37
+ self._time = self._test.get("time", time)
38
+ self.was_killed = self._test.get("Event", Event)()
39
+ atexit.register(self._atexit_signal)
40
+ self.start()
41
+
42
+ def _atexit_signal(self):
43
+ """
44
+ Non-joining shutdown signal.
45
+ Avoids deadlocks at interpreter exit from other threads, dead forks, etc.
46
+ This daemon thread is auto-reaped on shutdown without needing a join.
47
+ """
48
+ self.was_killed.set()
49
+
50
+ def exit(self):
51
+ self.was_killed.set()
52
+ if self is not current_thread():
53
+ self.join()
54
+ return self.report()
55
+
56
+ def get_instances(self):
57
+ # returns a copy of started `tqdm_cls` instances
58
+ return [i for i in self.tqdm_cls._instances.copy()
59
+ # Avoid race by checking that the instance started
60
+ if hasattr(i, 'start_t')]
61
+
62
+ def run(self):
63
+ cur_t = self._time()
64
+ while True:
65
+ # After processing and before sleeping, notify that we woke
66
+ # Need to be done just before sleeping
67
+ self.woken = cur_t
68
+ # Sleep some time...
69
+ self.was_killed.wait(self.sleep_interval)
70
+ # Quit if killed
71
+ if self.was_killed.is_set():
72
+ return
73
+ # Then monitor!
74
+ # Acquire lock (to access _instances)
75
+ with self.tqdm_cls.get_lock():
76
+ cur_t = self._time()
77
+ # Check tqdm instances are waiting too long to print
78
+ instances = self.get_instances()
79
+ for instance in instances:
80
+ # Check event in loop to reduce blocking time on exit
81
+ if self.was_killed.is_set():
82
+ return
83
+ # Only if mininterval > 1 (else iterations are just slow)
84
+ # and last refresh exceeded maxinterval
85
+ if (
86
+ instance.miniters > 1
87
+ and (cur_t - instance.last_print_t) >= instance.maxinterval
88
+ ):
89
+ # force bypassing miniters on next iteration
90
+ # (dynamic_miniters adjusts mininterval automatically)
91
+ instance.miniters = 1
92
+ # Refresh now! (works only for manual tqdm)
93
+ instance.refresh(nolock=True)
94
+ # Remove accidental long-lived strong reference
95
+ del instance
96
+ if instances != self.get_instances(): # pragma: nocover
97
+ warn("Set changed size during iteration" +
98
+ " (see https://github.com/tqdm/tqdm/issues/481)",
99
+ TqdmSynchronisationWarning, stacklevel=2)
100
+ # Remove accidental long-lived strong references
101
+ del instances
102
+
103
+ def report(self):
104
+ return not self.was_killed.is_set()
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/_tqdm.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from warnings import warn
2
+
3
+ from .std import * # NOQA
4
+ from .std import __all__ # NOQA
5
+ from .std import TqdmDeprecationWarning
6
+
7
+ warn("This function will be removed in tqdm==5.0.0\n"
8
+ "Please use `tqdm.std.*` instead of `tqdm._tqdm.*`",
9
+ TqdmDeprecationWarning, stacklevel=2)
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/_tqdm_gui.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from warnings import warn
2
+
3
+ from .gui import * # NOQA
4
+ from .gui import __all__ # NOQA
5
+ from .std import TqdmDeprecationWarning
6
+
7
+ warn("This function will be removed in tqdm==5.0.0\n"
8
+ "Please use `tqdm.gui.*` instead of `tqdm._tqdm_gui.*`",
9
+ TqdmDeprecationWarning, stacklevel=2)
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/_tqdm_notebook.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from warnings import warn
2
+
3
+ from .notebook import * # NOQA
4
+ from .notebook import __all__ # NOQA
5
+ from .std import TqdmDeprecationWarning
6
+
7
+ warn("This function will be removed in tqdm==5.0.0\n"
8
+ "Please use `tqdm.notebook.*` instead of `tqdm._tqdm_notebook.*`",
9
+ TqdmDeprecationWarning, stacklevel=2)
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/_tqdm_pandas.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ __author__ = "github.com/casperdcl"
4
+ __all__ = ['tqdm_pandas']
5
+
6
+
7
+ def tqdm_pandas(tclass, **tqdm_kwargs):
8
+ """
9
+ Registers the given `tqdm` instance with
10
+ `pandas.core.groupby.DataFrameGroupBy.progress_apply`.
11
+ """
12
+ from tqdm import TqdmDeprecationWarning
13
+
14
+ if isinstance(tclass, type) or (getattr(tclass, '__name__', '').startswith(
15
+ 'tqdm_')): # delayed adapter case
16
+ TqdmDeprecationWarning(
17
+ "Please use `tqdm.pandas(...)` instead of `tqdm_pandas(tqdm, ...)`.",
18
+ fp_write=getattr(tqdm_kwargs.get('file', None), 'write', sys.stderr.write))
19
+ tclass.pandas(**tqdm_kwargs)
20
+ else:
21
+ TqdmDeprecationWarning(
22
+ "Please use `tqdm.pandas(...)` instead of `tqdm_pandas(tqdm(...))`.",
23
+ fp_write=getattr(tclass.fp, 'write', sys.stderr.write))
24
+ type(tclass).pandas(deprecated_t=tclass)
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/_utils.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from warnings import warn
2
+
3
+ from .std import TqdmDeprecationWarning
4
+ from .utils import ( # noqa: F401, pylint: disable=unused-import
5
+ CUR_OS, IS_NIX, IS_WIN, RE_ANSI, Comparable, FormatReplace, SimpleTextIOWrapper,
6
+ _environ_cols_wrapper, _is_ascii, _is_utf, _screen_shape_linux, _screen_shape_tput,
7
+ _screen_shape_windows, _screen_shape_wrapper, _supports_unicode, _term_move_up, colorama)
8
+
9
+ warn("This function will be removed in tqdm==5.0.0\n"
10
+ "Please use `tqdm.utils.*` instead of `tqdm._utils.*`",
11
+ TqdmDeprecationWarning, stacklevel=2)
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/asyncio.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Asynchronous progress bar decorator for iterators.
3
+ Includes a default `range` iterator printing to `stderr`.
4
+
5
+ Usage:
6
+ >>> from tqdm.asyncio import trange, tqdm
7
+ >>> async for i in trange(10):
8
+ ... ...
9
+ """
10
+ import asyncio
11
+ from sys import version_info
12
+
13
+ from .std import tqdm as std_tqdm
14
+
15
+ __author__ = {"github.com/": ["casperdcl"]}
16
+ __all__ = ['tqdm_asyncio', 'tarange', 'tqdm', 'trange']
17
+
18
+
19
+ class tqdm_asyncio(std_tqdm):
20
+ """
21
+ Asynchronous-friendly version of tqdm.
22
+ """
23
+ def __init__(self, iterable=None, *args, **kwargs):
24
+ super().__init__(iterable, *args, **kwargs)
25
+ self.iterable_awaitable = False
26
+ if iterable is not None:
27
+ if hasattr(iterable, "__anext__"):
28
+ self.iterable_next = iterable.__anext__
29
+ self.iterable_awaitable = True
30
+ elif hasattr(iterable, "__aiter__"):
31
+ self.iterable_iterator = iterable.__aiter__()
32
+ self.iterable_next = self.iterable_iterator.__anext__
33
+ self.iterable_awaitable = True
34
+ elif hasattr(iterable, "__next__"):
35
+ self.iterable_next = iterable.__next__
36
+ else:
37
+ self.iterable_iterator = iter(iterable)
38
+ self.iterable_next = self.iterable_iterator.__next__
39
+
40
+ def __aiter__(self):
41
+ return self
42
+
43
+ async def __anext__(self):
44
+ try:
45
+ if self.iterable_awaitable:
46
+ res = await self.iterable_next()
47
+ else:
48
+ res = self.iterable_next()
49
+ self.update()
50
+ return res
51
+ except StopIteration:
52
+ self.close()
53
+ raise StopAsyncIteration
54
+ except BaseException:
55
+ self.close()
56
+ raise
57
+
58
+ def send(self, *args, **kwargs):
59
+ return self.iterable.send(*args, **kwargs)
60
+
61
+ @classmethod
62
+ def as_completed(cls, fs, *, loop=None, timeout=None, total=None, **tqdm_kwargs):
63
+ """
64
+ Wrapper for `asyncio.as_completed`.
65
+ """
66
+ if total is None:
67
+ total = len(fs)
68
+ kwargs = {}
69
+ if version_info[:2] < (3, 10):
70
+ kwargs['loop'] = loop
71
+ yield from cls(asyncio.as_completed(fs, timeout=timeout, **kwargs),
72
+ total=total, **tqdm_kwargs)
73
+
74
+ @classmethod
75
+ async def gather(cls, *fs, loop=None, timeout=None, total=None, return_exceptions=False,
76
+ **tqdm_kwargs):
77
+ """
78
+ Wrapper for `asyncio.gather`.
79
+ """
80
+ async def wrap_awaitable(i, f):
81
+ try:
82
+ return i, await f
83
+ except Exception as e: # noqa: BLE001
84
+ if return_exceptions:
85
+ return i, e
86
+ raise
87
+
88
+ ifs = [wrap_awaitable(i, f) for i, f in enumerate(fs)]
89
+ res = [await f for f in cls.as_completed(ifs, loop=loop, timeout=timeout,
90
+ total=total, **tqdm_kwargs)]
91
+ return [i for _, i in sorted(res)]
92
+
93
+
94
+ def tarange(*args, **kwargs):
95
+ """
96
+ A shortcut for `tqdm.asyncio.tqdm(range(*args), **kwargs)`.
97
+ """
98
+ return tqdm_asyncio(range(*args), **kwargs)
99
+
100
+
101
+ # Aliases
102
+ tqdm = tqdm_asyncio
103
+ trange = tarange
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/auto.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Enables multiple commonly used features.
3
+
4
+ Method resolution order:
5
+
6
+ - `tqdm.autonotebook` without import warnings
7
+ - `tqdm.asyncio`
8
+ - `tqdm.std` base class
9
+
10
+ Usage:
11
+ >>> from tqdm.auto import trange, tqdm
12
+ >>> for i in trange(10):
13
+ ... ...
14
+ """
15
+ import warnings
16
+
17
+ from .std import TqdmExperimentalWarning
18
+
19
+ with warnings.catch_warnings():
20
+ warnings.simplefilter("ignore", category=TqdmExperimentalWarning)
21
+ from .autonotebook import tqdm as notebook_tqdm
22
+
23
+ from .asyncio import tqdm as asyncio_tqdm
24
+ from .std import tqdm as std_tqdm
25
+
26
+ if notebook_tqdm != std_tqdm:
27
+ class tqdm(notebook_tqdm, asyncio_tqdm): # pylint: disable=inconsistent-mro
28
+ pass
29
+ else:
30
+ tqdm = asyncio_tqdm
31
+
32
+
33
+ def trange(*args, **kwargs):
34
+ """
35
+ A shortcut for `tqdm.auto.tqdm(range(*args), **kwargs)`.
36
+ """
37
+ return tqdm(range(*args), **kwargs)
38
+
39
+
40
+ __all__ = ["tqdm", "trange"]
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/autonotebook.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Automatically choose between `tqdm.notebook` and `tqdm.std`.
3
+
4
+ Usage:
5
+ >>> from tqdm.autonotebook import trange, tqdm
6
+ >>> for i in trange(10):
7
+ ... ...
8
+ """
9
+ import os
10
+ import sys
11
+ from warnings import warn
12
+
13
+ try:
14
+ if 'ipykernel.zmqshell' in sys.modules:
15
+ if any(i == 'QT_API' or i.startswith('SPYDER') for i in os.environ):
16
+ raise ImportError("console") # jupyter-qtconsole/spyder
17
+ ipy = sys.modules['IPython'].get_ipython().__class__.__name__.lower()
18
+ if 'qt' in ipy or 'spyder' in ipy:
19
+ raise ImportError("console") # older jupyter-qtconsole/spyder
20
+ # jupyter-notebook/jupyterlab/vscode/binder/colab
21
+ elif 'IPython.utils._process_emscripten' in sys.modules:
22
+ pass # jupyterlite (pyodide)/jupyterlite-xeus
23
+ else:
24
+ raise ImportError("console") # ipython/jupyter-console
25
+ from .notebook import WARN_NOIPYW, IProgress
26
+ if IProgress is None:
27
+ from .std import TqdmWarning
28
+ warn(WARN_NOIPYW, TqdmWarning, stacklevel=2)
29
+ raise ImportError('ipywidgets')
30
+ except Exception:
31
+ from .std import tqdm, trange
32
+ else: # pragma: no cover
33
+ from .notebook import tqdm, trange
34
+ from .std import TqdmExperimentalWarning
35
+ warn("Using `tqdm.autonotebook.tqdm` in notebook mode."
36
+ " Use `tqdm.tqdm` instead to force console mode"
37
+ " (e.g. in jupyter console)", TqdmExperimentalWarning, stacklevel=2)
38
+ __all__ = ["tqdm", "trange"]
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/cli.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Module version for monitoring CLI pipes (`... | python -m tqdm | ...`).
3
+ """
4
+ import logging
5
+ import re
6
+ import sys
7
+ from ast import literal_eval
8
+ from textwrap import indent
9
+
10
+ from .std import TqdmKeyError, TqdmTypeError, tqdm
11
+ from .version import __version__
12
+
13
+ __all__ = ["main"]
14
+ log = logging.getLogger(__name__)
15
+
16
+
17
+ def cast(val, typ):
18
+ log.debug((val, typ))
19
+ if " or " in typ:
20
+ for t in typ.split(" or "):
21
+ try:
22
+ return cast(val, t)
23
+ except TqdmTypeError:
24
+ pass
25
+ raise TqdmTypeError(f"{val} : {typ}")
26
+
27
+ # sys.stderr.write('\ndebug | `val:type`: `' + val + ':' + typ + '`.\n')
28
+ if typ == 'bool':
29
+ if (val == 'True') or (val == ''):
30
+ return True
31
+ if val == 'False':
32
+ return False
33
+ raise TqdmTypeError(val + ' : ' + typ)
34
+ if typ == 'chr':
35
+ if len(val) == 1:
36
+ return val.encode()
37
+ if re.match(r"^\\\w+$", val):
38
+ return literal_eval(f'"{val}"').encode()
39
+ raise TqdmTypeError(f"{val} : {typ}")
40
+ if typ == 'str':
41
+ return val
42
+ if typ == 'int':
43
+ try:
44
+ return int(val)
45
+ except ValueError as exc:
46
+ raise TqdmTypeError(f"{val} : {typ}") from exc
47
+ if typ == 'float':
48
+ try:
49
+ return float(val)
50
+ except ValueError as exc:
51
+ raise TqdmTypeError(f"{val} : {typ}") from exc
52
+ raise TqdmTypeError(f"{val} : {typ}")
53
+
54
+
55
+ def posix_pipe(fin, fout, delim=b'\\n', buf_size=256,
56
+ callback=lambda float: None, callback_len=True):
57
+ """
58
+ Params
59
+ ------
60
+ fin : binary file with `read(buf_size : int)` method
61
+ fout : binary file with `write` (and optionally `flush`) methods.
62
+ callback : function(float), e.g.: `tqdm.update`
63
+ callback_len : If (default: True) do `callback(len(buffer))`.
64
+ Otherwise, do `callback(data) for data in buffer.split(delim)`.
65
+ """
66
+ fp_write = fout.write
67
+
68
+ if not delim:
69
+ while True:
70
+ tmp = fin.read(buf_size)
71
+
72
+ # flush at EOF
73
+ if not tmp:
74
+ getattr(fout, 'flush', lambda: None)()
75
+ return
76
+
77
+ fp_write(tmp)
78
+ callback(len(tmp))
79
+ # return
80
+
81
+ buf = b''
82
+ len_delim = len(delim)
83
+ # n = 0
84
+ while True:
85
+ tmp = fin.read(buf_size)
86
+
87
+ # flush at EOF
88
+ if not tmp:
89
+ if buf:
90
+ fp_write(buf)
91
+ if callback_len:
92
+ # n += 1 + buf.count(delim)
93
+ callback(1 + buf.count(delim))
94
+ else:
95
+ for i in buf.split(delim):
96
+ callback(i)
97
+ getattr(fout, 'flush', lambda: None)()
98
+ return # n
99
+
100
+ while True:
101
+ i = tmp.find(delim)
102
+ if i < 0:
103
+ buf += tmp
104
+ break
105
+ fp_write(buf + tmp[:i + len(delim)])
106
+ # n += 1
107
+ callback(1 if callback_len else (buf + tmp[:i]))
108
+ buf = b''
109
+ tmp = tmp[i + len_delim:]
110
+
111
+
112
+ # ((opt, type), ... )
113
+ RE_OPTS = re.compile(r'\n {4}(\S+)\s{2,}:\s*([^,]+)')
114
+ # better split method assuming no positional args
115
+ RE_SHLEX = re.compile(r'\s*(?<!\S)--?([^\s=]+)(\s+|=|$)')
116
+
117
+ # TODO: add custom support for some of the following?
118
+ UNSUPPORTED_OPTS = ('iterable', 'gui', 'out', 'file')
119
+
120
+ # The 8 leading spaces are required for consistency
121
+ CLI_EXTRA_DOC = r"""
122
+ Extra CLI Options
123
+ -----------------
124
+ name : type, optional
125
+ TODO: find out why this is needed.
126
+ delim : chr, optional
127
+ Delimiting character [default: '\n']. Use '\0' for null.
128
+ N.B.: on Windows systems, Python converts '\n' to '\r\n'.
129
+ buf_size : int, optional
130
+ String buffer size in bytes [default: 256]
131
+ used when `delim` is specified.
132
+ bytes : bool, optional
133
+ If true, will count bytes, ignore `delim`, and default
134
+ `unit_scale` to True, `unit_divisor` to 1024, and `unit` to 'B'.
135
+ tee : bool, optional
136
+ If true, passes `stdin` to both `stderr` and `stdout`.
137
+ update : bool, optional
138
+ If true, will treat input as newly elapsed iterations,
139
+ i.e. numbers to pass to `update()`. Note that this is slow
140
+ (~2e5 it/s) since every input must be decoded as a number.
141
+ update_to : bool, optional
142
+ If true, will treat input as total elapsed iterations,
143
+ i.e. numbers to assign to `self.n`. Note that this is slow
144
+ (~2e5 it/s) since every input must be decoded as a number.
145
+ null : bool, optional
146
+ If true, will discard input (no stdout).
147
+ manpath : str, optional
148
+ Directory in which to install tqdm man pages.
149
+ comppath : str, optional
150
+ Directory in which to place tqdm completion.
151
+ log : str, optional
152
+ CRITICAL|FATAL|ERROR|WARN(ING)|[default: 'INFO']|DEBUG|NOTSET.
153
+ """
154
+
155
+
156
+ def main(fp=sys.stderr, argv=None):
157
+ """
158
+ Parameters (internal use only)
159
+ ---------
160
+ fp : file-like object for tqdm
161
+ argv : list (default: sys.argv[1:])
162
+ """
163
+ if argv is None:
164
+ argv = sys.argv[1:]
165
+ try:
166
+ log_idx = argv.index('--log')
167
+ except ValueError:
168
+ for i in argv:
169
+ if i.startswith('--log='):
170
+ logLevel = i[len('--log='):]
171
+ break
172
+ else:
173
+ logLevel = 'INFO'
174
+ else:
175
+ # argv.pop(log_idx)
176
+ # logLevel = argv.pop(log_idx)
177
+ logLevel = argv[log_idx + 1]
178
+ logging.basicConfig(level=getattr(logging, logLevel),
179
+ format="%(levelname)s:%(module)s:%(lineno)d:%(message)s")
180
+
181
+ # py<3.13 doesn't dedent docstrings
182
+ d = (tqdm.__doc__ if sys.version_info < (3, 13)
183
+ else indent(tqdm.__doc__, " ")) + CLI_EXTRA_DOC
184
+
185
+ opt_types = dict(RE_OPTS.findall(d))
186
+ # opt_types['delim'] = 'chr'
187
+
188
+ for o in UNSUPPORTED_OPTS:
189
+ opt_types.pop(o)
190
+
191
+ log.debug(sorted(opt_types.items()))
192
+
193
+ # d = RE_OPTS.sub(r' --\1=<\1> : \2', d)
194
+ split = RE_OPTS.split(d)
195
+ opt_types_desc = zip(split[1::3], split[2::3], split[3::3])
196
+ d = ''.join(('\n --{0} : {2}{3}' if otd[1] == 'bool' else
197
+ '\n --{0}=<{1}> : {2}{3}').format(
198
+ otd[0].replace('_', '-'), otd[0], *otd[1:])
199
+ for otd in opt_types_desc if otd[0] not in UNSUPPORTED_OPTS)
200
+
201
+ help_short = "Usage:\n tqdm [--help | options]\n"
202
+ d = help_short + """
203
+ Options:
204
+ -h, --help Print this help and exit.
205
+ -v, --version Print version and exit.
206
+ """ + d.strip('\n') + '\n'
207
+
208
+ # opts = docopt(d, version=__version__)
209
+ if any(v in argv for v in ('-v', '--version')):
210
+ sys.stdout.write(__version__ + '\n')
211
+ sys.exit(0)
212
+ elif any(v in argv for v in ('-h', '--help')):
213
+ sys.stdout.write(d + '\n')
214
+ sys.exit(0)
215
+ elif argv and argv[0][:2] != '--':
216
+ sys.stderr.write(f"Error:Unknown argument:{argv[0]}\n{help_short}")
217
+
218
+ argv = RE_SHLEX.split(' '.join(["tqdm"] + argv))
219
+ opts = dict(zip(argv[1::3], argv[3::3]))
220
+
221
+ log.debug(opts)
222
+ opts.pop('log', True)
223
+
224
+ tqdm_args = {'file': fp}
225
+ try:
226
+ for (o, v) in opts.items():
227
+ o = o.replace('-', '_')
228
+ try:
229
+ tqdm_args[o] = cast(v, opt_types[o])
230
+ except KeyError as e:
231
+ raise TqdmKeyError(str(e))
232
+ log.debug('args:' + str(tqdm_args))
233
+
234
+ delim_per_char = tqdm_args.pop('bytes', False)
235
+ update = tqdm_args.pop('update', False)
236
+ update_to = tqdm_args.pop('update_to', False)
237
+ if sum((delim_per_char, update, update_to)) > 1:
238
+ raise TqdmKeyError("Can only have one of --bytes --update --update_to")
239
+ except Exception:
240
+ fp.write("\nError:\n" + help_short)
241
+ stdin, stdout_write = sys.stdin, sys.stdout.write
242
+ for i in stdin:
243
+ stdout_write(i)
244
+ raise
245
+ else:
246
+ buf_size = tqdm_args.pop('buf_size', 256)
247
+ delim = tqdm_args.pop('delim', b'\\n')
248
+ tee = tqdm_args.pop('tee', False)
249
+ manpath = tqdm_args.pop('manpath', None)
250
+ comppath = tqdm_args.pop('comppath', None)
251
+ if tqdm_args.pop('null', False):
252
+ class stdout:
253
+ @staticmethod
254
+ def write(_):
255
+ pass
256
+ else:
257
+ stdout = sys.stdout
258
+ stdout = getattr(stdout, 'buffer', stdout)
259
+ stdin = getattr(sys.stdin, 'buffer', sys.stdin)
260
+ if manpath or comppath:
261
+ try: # py<3.9
262
+ import importlib_resources as resources
263
+ except ImportError:
264
+ from importlib import resources
265
+ from pathlib import Path
266
+
267
+ def cp(name, dst):
268
+ """copy resource `name` to `dst`"""
269
+ fi = resources.files('tqdm') / name
270
+ dst.write_bytes(fi.read_bytes())
271
+ log.info("written:%s", dst)
272
+ if manpath is not None:
273
+ cp('tqdm.1', Path(manpath) / 'tqdm.1')
274
+ if comppath is not None:
275
+ cp('completion.sh', Path(comppath) / 'tqdm_completion.sh')
276
+ sys.exit(0)
277
+ if tee:
278
+ stdout_write = stdout.write
279
+ fp_write = getattr(fp, 'buffer', fp).write
280
+
281
+ class stdout: # pylint: disable=function-redefined
282
+ @staticmethod
283
+ def write(x):
284
+ with tqdm.external_write_mode(file=fp):
285
+ fp_write(x)
286
+ stdout_write(x)
287
+ if delim_per_char:
288
+ tqdm_args.setdefault('unit', 'B')
289
+ tqdm_args.setdefault('unit_scale', True)
290
+ tqdm_args.setdefault('unit_divisor', 1024)
291
+ log.debug(tqdm_args)
292
+ with tqdm(**tqdm_args) as t:
293
+ posix_pipe(stdin, stdout, '', buf_size, t.update)
294
+ elif delim == b'\\n':
295
+ log.debug(tqdm_args)
296
+ write = stdout.write
297
+ if update or update_to:
298
+ with tqdm(**tqdm_args) as t:
299
+ if update:
300
+ def callback(i):
301
+ t.update(literal_eval(i.decode()))
302
+ else: # update_to
303
+ def callback(i):
304
+ t.update(literal_eval(i.decode()) - t.n)
305
+ for i in stdin:
306
+ write(i)
307
+ callback(i)
308
+ else:
309
+ for i in tqdm(stdin, **tqdm_args):
310
+ write(i)
311
+ else:
312
+ log.debug(tqdm_args)
313
+ with tqdm(**tqdm_args) as t:
314
+ callback_len = False
315
+ if update:
316
+ def callback(i):
317
+ t.update(literal_eval(i.decode()))
318
+ elif update_to:
319
+ def callback(i):
320
+ t.update(literal_eval(i.decode()) - t.n)
321
+ else:
322
+ callback = t.update
323
+ callback_len = True
324
+ posix_pipe(stdin, stdout, delim, buf_size, callback, callback_len)
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/completion.sh ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ _tqdm(){
3
+ local cur prv
4
+ cur="${COMP_WORDS[COMP_CWORD]}"
5
+ prv="${COMP_WORDS[COMP_CWORD - 1]}"
6
+
7
+ case ${prv} in
8
+ --bar_format|--buf_size|--colour|--comppath|--delay|--delim|--desc|--initial|--lock_args|--manpath|--maxinterval|--mininterval|--miniters|--ncols|--nrows|--position|--postfix|--smoothing|--total|--unit|--unit_divisor)
9
+ # await user input
10
+ ;;
11
+ "--log")
12
+ COMPREPLY=($(compgen -W 'CRITICAL FATAL ERROR WARN WARNING INFO DEBUG NOTSET' -- ${cur}))
13
+ ;;
14
+ *)
15
+ COMPREPLY=($(compgen -W '--ascii --bar_format --buf_size --bytes --colour --comppath --delay --delim --desc --disable --dynamic_ncols --help --initial --leave --lock_args --log --manpath --maxinterval --mininterval --miniters --ncols --nrows --null --position --postfix --smoothing --tee --total --unit --unit_divisor --unit_scale --update --update_to --version --write_bytes -h -v' -- ${cur}))
16
+ ;;
17
+ esac
18
+ }
19
+ complete -F _tqdm tqdm
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/contrib/__init__.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Thin wrappers around common functions.
3
+
4
+ Subpackages contain potentially unstable extensions.
5
+ """
6
+ from warnings import warn
7
+
8
+ from ..auto import tqdm as tqdm_auto
9
+ from ..std import TqdmDeprecationWarning, tqdm
10
+ from ..utils import ObjectWrapper
11
+
12
+ __author__ = {"github.com/": ["casperdcl"]}
13
+ __all__ = ['tenumerate', 'tzip', 'tmap']
14
+
15
+
16
+ class DummyTqdmFile(ObjectWrapper):
17
+ """Dummy file-like that will write to tqdm"""
18
+
19
+ def __init__(self, wrapped):
20
+ super().__init__(wrapped)
21
+ self._buf = []
22
+
23
+ def write(self, x, nolock=False):
24
+ nl = b"\n" if isinstance(x, bytes) else "\n"
25
+ pre, sep, post = x.rpartition(nl)
26
+ if sep:
27
+ blank = type(nl)()
28
+ tqdm.write(blank.join(self._buf + [pre, sep]),
29
+ end=blank, file=self._wrapped, nolock=nolock)
30
+ self._buf = [post]
31
+ else:
32
+ self._buf.append(x)
33
+
34
+ def __del__(self):
35
+ if self._buf:
36
+ blank = type(self._buf[0])()
37
+ try:
38
+ tqdm.write(blank.join(self._buf), end=blank, file=self._wrapped)
39
+ except (OSError, ValueError):
40
+ pass
41
+
42
+
43
+ def builtin_iterable(func):
44
+ """Returns `func`"""
45
+ warn("This function has no effect, and will be removed in tqdm==5.0.0",
46
+ TqdmDeprecationWarning, stacklevel=2)
47
+ return func
48
+
49
+
50
+ def tenumerate(iterable, start=0, total=None, tqdm_class=tqdm_auto, **tqdm_kwargs):
51
+ """
52
+ Equivalent of `numpy.ndenumerate` or builtin `enumerate`.
53
+
54
+ Parameters
55
+ ----------
56
+ tqdm_class : [default: tqdm.auto.tqdm].
57
+ """
58
+ try:
59
+ import numpy as np
60
+ except ImportError:
61
+ pass
62
+ else:
63
+ if isinstance(iterable, np.ndarray):
64
+ return tqdm_class(np.ndenumerate(iterable), total=total or iterable.size,
65
+ **tqdm_kwargs)
66
+ return enumerate(tqdm_class(iterable, total=total, **tqdm_kwargs), start)
67
+
68
+
69
+ def tzip(iter1, *iter2plus, **tqdm_kwargs):
70
+ """
71
+ Equivalent of builtin `zip`.
72
+
73
+ Parameters
74
+ ----------
75
+ tqdm_class : [default: tqdm.auto.tqdm].
76
+ """
77
+ kwargs = tqdm_kwargs.copy()
78
+ tqdm_class = kwargs.pop("tqdm_class", tqdm_auto)
79
+ yield from zip(tqdm_class(iter1, **kwargs), *iter2plus)
80
+
81
+
82
+ def tmap(function, *sequences, **tqdm_kwargs):
83
+ """
84
+ Equivalent of builtin `map`.
85
+
86
+ Parameters
87
+ ----------
88
+ tqdm_class : [default: tqdm.auto.tqdm].
89
+ """
90
+ for i in tzip(*sequences, **tqdm_kwargs):
91
+ yield function(*i)
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/contrib/bells.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Even more features than `tqdm.auto` (all the bells & whistles):
3
+
4
+ - `tqdm.auto`
5
+ - `tqdm.tqdm.pandas`
6
+ - `tqdm.contrib.slack`
7
+ + uses `${TQDM_SLACK_TOKEN}` and `${TQDM_SLACK_CHANNEL}`
8
+ - `tqdm.contrib.telegram`
9
+ + uses `${TQDM_TELEGRAM_TOKEN}` and `${TQDM_TELEGRAM_CHAT_ID}`
10
+ - `tqdm.contrib.discord`
11
+ + uses `${TQDM_DISCORD_TOKEN}` and `${TQDM_DISCORD_CHANNEL_ID}`
12
+ """
13
+ __all__ = ['tqdm', 'trange']
14
+ import warnings
15
+ from os import getenv
16
+
17
+ if getenv("TQDM_SLACK_TOKEN") and getenv("TQDM_SLACK_CHANNEL"):
18
+ from .slack import tqdm, trange
19
+ elif getenv("TQDM_TELEGRAM_TOKEN") and getenv("TQDM_TELEGRAM_CHAT_ID"):
20
+ from .telegram import tqdm, trange
21
+ elif getenv("TQDM_DISCORD_TOKEN") and getenv("TQDM_DISCORD_CHANNEL_ID"):
22
+ from .discord import tqdm, trange
23
+ else:
24
+ from ..auto import tqdm, trange
25
+
26
+ with warnings.catch_warnings():
27
+ warnings.simplefilter("ignore", category=FutureWarning)
28
+ tqdm.pandas()
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/contrib/concurrent.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Thin wrappers around `concurrent.futures`.
3
+ """
4
+ import sys
5
+ from contextlib import contextmanager
6
+ from operator import length_hint
7
+
8
+ from ..auto import tqdm as tqdm_auto
9
+ from ..std import TqdmWarning
10
+
11
+ __author__ = {"github.com/": ["casperdcl"]}
12
+ __all__ = ['thread_map', 'process_map', 'interpreter_map']
13
+
14
+
15
+ class _InterpreterLock:
16
+ """Reentrant lock backed by a cross-interpreter queue."""
17
+ from threading import get_ident
18
+ from time import monotonic as _time
19
+
20
+ def __init__(self, queue):
21
+ from threading import RLock
22
+ self._queue = queue
23
+ self._lock = RLock()
24
+ self._owner = None
25
+ self._depth = 0
26
+
27
+ def acquire(self, blocking=True, timeout=-1):
28
+ from queue import Empty
29
+ start = self._time()
30
+ if timeout == -1:
31
+ acquired = self._lock.acquire(blocking)
32
+ else:
33
+ acquired = self._lock.acquire(blocking, timeout)
34
+ if not acquired:
35
+ return False
36
+ if self._depth:
37
+ self._depth += 1
38
+ return True
39
+ try:
40
+ if not blocking:
41
+ self._queue.get_nowait()
42
+ elif timeout == -1:
43
+ self._queue.get()
44
+ else:
45
+ remaining = max(0, timeout - (self._time() - start))
46
+ self._queue.get(timeout=remaining)
47
+ except Empty:
48
+ self._lock.release()
49
+ return False
50
+ self._owner = self.get_ident()
51
+ self._depth = 1
52
+ return True
53
+
54
+ def release(self):
55
+ if self._owner != self.get_ident():
56
+ raise RuntimeError("cannot release un-acquired lock")
57
+ self._depth -= 1
58
+ if not self._depth:
59
+ self._owner = None
60
+ self._queue.put(None)
61
+ self._lock.release()
62
+
63
+ def __enter__(self):
64
+ self.acquire()
65
+ return self
66
+
67
+ def __exit__(self, *exc):
68
+ self.release()
69
+
70
+
71
+ @contextmanager
72
+ def ensure_lock(tqdm_class, lock_name="", lock=None):
73
+ """get (create if necessary) and then restore `tqdm_class`'s lock"""
74
+ old_lock = getattr(tqdm_class, '_lock', None) # don't create a new lock
75
+ if lock is None:
76
+ lock = old_lock or tqdm_class.get_lock() # maybe create a new lock
77
+ lock = getattr(lock, lock_name, lock) # maybe subtype
78
+ tqdm_class.set_lock(lock)
79
+ yield lock
80
+ if old_lock is None:
81
+ del tqdm_class._lock
82
+ else:
83
+ tqdm_class.set_lock(old_lock)
84
+
85
+
86
+ def _get_interpreter_init(tqdm_class, lock_queue_id):
87
+ """Return an initializer which bootstraps the parent import path and lock."""
88
+ code = (
89
+ "import sys\n"
90
+ f"sys.path[:] = {sys.path!r}\n"
91
+ "from concurrent import interpreters\n"
92
+ "from importlib import import_module\n"
93
+ "from tqdm.contrib.concurrent import _InterpreterLock\n"
94
+ f"tqdm_class = import_module({tqdm_class.__module__!r})\n"
95
+ f"for name in {tqdm_class.__qualname__.split('.')!r}:\n"
96
+ " tqdm_class = getattr(tqdm_class, name)\n"
97
+ "tqdm_class.monitor_interval = 0\n"
98
+ f"tqdm_class.set_lock(_InterpreterLock(interpreters.Queue({lock_queue_id!r})))")
99
+ return exec, (code,)
100
+
101
+
102
+ def _min_map_len(iterables):
103
+ """min(map(length_hint, iterables), default=0)"""
104
+ return min((n for it in iterables if (n := length_hint(it, -1)) >= 0), default=0)
105
+
106
+
107
+ def _executor_map(
108
+ PoolExecutor, fn, *iterables, max_workers=None, timeout=None, chunksize=1, lock_name="",
109
+ tqdm_class=tqdm_auto, smoothing=0.0, _lock=None, _initializer=None, _initargs=None,
110
+ **tqdm_kwargs
111
+ ):
112
+ """
113
+ Implementation of `thread_map`, `process_map` and `interpreter_map`.
114
+
115
+ Parameters
116
+ ----------
117
+ max_workers : int
118
+ timeout : int
119
+ buffersize : int
120
+ Requires Python>=3.14.
121
+ thread_name_prefix : str
122
+ max_tasks_per_child : int
123
+ mp_context : str
124
+ """
125
+ kwargs = tqdm_kwargs.copy()
126
+ if 'total' not in kwargs:
127
+ kwargs['total'] = _min_map_len(iterables)
128
+ map_kwargs = {}
129
+ if 'buffersize' in kwargs:
130
+ map_kwargs['buffersize'] = kwargs.pop('buffersize')
131
+ pool_kwargs = {}
132
+ for k in ('thread_name_prefix', 'max_tasks_per_child', 'mp_context'):
133
+ if k in kwargs:
134
+ pool_kwargs[k] = kwargs.pop(k)
135
+ dynamic_miniters = None
136
+ if kwargs['total'] and 'miniters' not in kwargs:
137
+ try:
138
+ from os import process_cpu_count as cpu_count
139
+ except ImportError:
140
+ from os import cpu_count
141
+ # thread & process pools have different default workers, but we KISS here
142
+ rough_max = max_workers or min(32, (cpu_count() or 1) + 4)
143
+ if kwargs['total'] > rough_max:
144
+ kwargs['miniters'] = rough_max
145
+ dynamic_miniters = True
146
+ with ensure_lock(tqdm_class, lock_name=lock_name, lock=_lock) as lk:
147
+ # share lock in case workers are already using `tqdm`
148
+ if _initializer is None:
149
+ _initializer = tqdm_class.set_lock
150
+ _initargs = (lk,)
151
+ with PoolExecutor(max_workers=max_workers, initializer=_initializer, initargs=_initargs,
152
+ **pool_kwargs) as ex:
153
+ with tqdm_class(smoothing=smoothing, **kwargs) as pbar:
154
+ if dynamic_miniters is not None:
155
+ pbar.dynamic_miniters = True
156
+ orisubmit = ex.submit
157
+
158
+ def patchsubmit(*args, **kwargs):
159
+ fut = orisubmit(*args, **kwargs)
160
+ fut.add_done_callback(lambda _: pbar.update())
161
+ return fut
162
+ ex.submit = patchsubmit
163
+ return list(ex.map(
164
+ fn, *iterables, timeout=timeout, chunksize=chunksize, **map_kwargs))
165
+
166
+
167
+ def thread_map(fn, *iterables, **tqdm_kwargs):
168
+ """
169
+ Equivalent of `list(map(fn, *iterables))`
170
+ driven by `concurrent.futures.ThreadPoolExecutor`.
171
+
172
+ Parameters
173
+ ----------
174
+ max_workers : int, optional
175
+ Maximum number of workers to spawn; passed to `concurrent.futures.ThreadPoolExecutor`.
176
+ thread_name_prefix : str, optional
177
+ Passed to `concurrent.futures.ThreadPoolExecutor` [default: ''].
178
+ timeout : int or float, optional
179
+ Seconds to wait before raising `TimeoutError` if `__next__` is called and the
180
+ result isn't available. [default: None].
181
+ buffersize : int, optional
182
+ Requires Python>=3.14 [default: None].
183
+ tqdm_class : optional
184
+ `tqdm` class to use for bars [default: tqdm.auto.tqdm].
185
+ smoothing : float, optional
186
+ Passed to `tqdm_class`; the [default: 0] is average (due to erratic update frequency).
187
+ lock_name : str, optional
188
+ Member of `tqdm_class.get_lock()` to use [default: ''].
189
+ """
190
+ from concurrent.futures import ThreadPoolExecutor
191
+ return _executor_map(ThreadPoolExecutor, fn, *iterables, **tqdm_kwargs)
192
+
193
+
194
+ def interpreter_map(fn, *iterables, **tqdm_kwargs):
195
+ """
196
+ Equivalent of `list(map(fn, *iterables))`
197
+ driven by `concurrent.futures.InterpreterPoolExecutor` (Python 3.14+).
198
+
199
+ Parameters
200
+ ----------
201
+ Same as `thread_map`.
202
+
203
+ Notes
204
+ -----
205
+ `fn`, its arguments, and its return values must be pickleable.
206
+ Worker progress bars using the same `tqdm_class` share a cross-interpreter write lock.
207
+ """
208
+ from concurrent import interpreters
209
+ from concurrent.futures import InterpreterPoolExecutor
210
+ lock_queue = interpreters.create_queue()
211
+ lock_queue.put(None)
212
+ tqdm_class = tqdm_kwargs.get("tqdm_class", tqdm_auto)
213
+ initializer, initargs = _get_interpreter_init(tqdm_class, lock_queue.id)
214
+ return _executor_map(
215
+ InterpreterPoolExecutor, fn, *iterables, _lock=_InterpreterLock(lock_queue),
216
+ _initializer=initializer, _initargs=initargs, **tqdm_kwargs)
217
+
218
+
219
+ def process_map(fn, *iterables, lock_name="mp_lock", **tqdm_kwargs):
220
+ """
221
+ Equivalent of `list(map(fn, *iterables))`
222
+ driven by `concurrent.futures.ProcessPoolExecutor`.
223
+
224
+ Parameters
225
+ ----------
226
+ max_workers : int, optional
227
+ Maximum number of workers to spawn; passed to `concurrent.futures.ProcessPoolExecutor`.
228
+ timeout : int or float, optional
229
+ Seconds to wait before raising `TimeoutError` if `__next__` is called and the
230
+ result isn't available. [default: None].
231
+ chunksize : int, optional
232
+ Approximate size of chunks sent to worker processes; passed to
233
+ `concurrent.futures.ProcessPoolExecutor.map`. [default: 1].
234
+ buffersize : int, optional
235
+ Requires Python>=3.14 [default: None].
236
+ max_tasks_per_child : int, optional
237
+ Maximum number of tasks a worker process can complete before being replaced
238
+ with a new process; passed to `concurrent.futures.ProcessPoolExecutor`.
239
+ mp_context : multiprocessing.BaseContext, optional
240
+ Multiprocessing context to use, e.g. `multiprocessing.get_context('fork')`.
241
+ lock_name : str, optional
242
+ Member of `tqdm_class.get_lock()` to use [default: mp_lock].
243
+ tqdm_class : optional
244
+ `tqdm` class to use for bars [default: tqdm.auto.tqdm].
245
+ smoothing : float, optional
246
+ Passed to `tqdm_class`; the [default: 0] is average (due to erratic update frequency).
247
+ """
248
+ from concurrent.futures import ProcessPoolExecutor
249
+ if iterables and 'chunksize' not in tqdm_kwargs:
250
+ # default `chunksize=1` has poor performance for large iterables
251
+ # (most time spent dispatching items to workers).
252
+ shortest_iterable_len = _min_map_len(iterables)
253
+ if shortest_iterable_len > 1000:
254
+ from warnings import warn
255
+ warn("Iterable length %d > 1000 but `chunksize` is not set."
256
+ " This may seriously degrade multiprocess performance."
257
+ " Set `chunksize=1` or more." % shortest_iterable_len,
258
+ TqdmWarning, stacklevel=2)
259
+ return _executor_map(ProcessPoolExecutor, fn, *iterables, lock_name=lock_name, **tqdm_kwargs)
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/contrib/discord.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Sends updates to a Discord bot.
3
+
4
+ Usage:
5
+ >>> from tqdm.contrib.discord import tqdm, trange
6
+ >>> for i in trange(10, token='{token}', channel_id='{channel_id}'):
7
+ ... ...
8
+
9
+ ![screenshot](https://tqdm.github.io/img/screenshot-discord.png)
10
+ """
11
+ from warnings import warn
12
+
13
+ from requests import Session
14
+ from requests.utils import default_user_agent
15
+
16
+ from ..auto import tqdm as tqdm_auto
17
+ from ..std import TqdmWarning
18
+ from ..utils import envwrap
19
+ from ..version import __version__
20
+ from .utils_worker import MonoWorker
21
+
22
+ __author__ = {"github.com/": ["casperdcl", "guigoruiz1"]}
23
+ __all__ = ['DiscordIO', 'tqdm_discord', 'tdrange', 'tqdm', 'trange']
24
+
25
+
26
+ class DiscordIO(MonoWorker):
27
+ """Non-blocking file-like IO using a Discord Bot."""
28
+ API = 'https://discord.com/api/v10'
29
+ UA = f"tqdm (https://tqdm.github.io, {__version__}) {default_user_agent()}"
30
+
31
+ def __init__(self, token, channel_id):
32
+ """Creates a new message in the given `channel_id`."""
33
+ super().__init__()
34
+ self.token = token
35
+ self.channel_id = channel_id
36
+ self.session = Session()
37
+ self.text = self.__class__.__name__
38
+ self.message_id # pylint: disable=pointless-statement
39
+
40
+ @property
41
+ def message_id(self):
42
+ if hasattr(self, '_message_id'):
43
+ return self._message_id # pylint: disable=access-member-before-definition
44
+ try:
45
+ req = self.session.post(
46
+ f'{self.API}/channels/{self.channel_id}/messages',
47
+ headers={'Authorization': f'Bot {self.token}', 'User-Agent': self.UA},
48
+ json={'content': f"`{self.text}`"})
49
+ res = req.json()
50
+ req.raise_for_status()
51
+ except Exception as e:
52
+ if req.status_code == 429:
53
+ warn("Creation rate limit: try increasing `mininterval`.",
54
+ TqdmWarning, stacklevel=2)
55
+ else:
56
+ tqdm_auto.write(str(e))
57
+ else:
58
+ self._message_id = res['id']
59
+ return self._message_id
60
+
61
+ def write(self, s):
62
+ """Replaces internal `message_id`'s text with `s`."""
63
+ if not s:
64
+ s = "..."
65
+ s = s.replace('\r', '').strip()
66
+ if s == self.text:
67
+ return # avoid duplicate message Bot error
68
+ message_id = self.message_id
69
+ if message_id is None:
70
+ return
71
+ self.text = s
72
+ try:
73
+ future = self.submit(
74
+ self.session.patch,
75
+ f'{self.API}/channels/{self.channel_id}/messages/{message_id}',
76
+ headers={'Authorization': f'Bot {self.token}', 'User-Agent': self.UA},
77
+ json={'content': f"`{self.text}`"})
78
+ except Exception as e:
79
+ tqdm_auto.write(str(e))
80
+ else:
81
+ return future
82
+
83
+ def delete(self):
84
+ """Deletes internal `message_id`."""
85
+ try:
86
+ future = self.submit(
87
+ self.session.delete,
88
+ f'{self.API}/channels/{self.channel_id}/messages/{self.message_id}',
89
+ headers={'Authorization': f'Bot {self.token}', 'User-Agent': self.UA})
90
+ except Exception as e:
91
+ tqdm_auto.write(str(e))
92
+ else:
93
+ return future
94
+
95
+
96
+ class tqdm_discord(tqdm_auto): # pylint: disable=inconsistent-mro
97
+ """
98
+ Standard `tqdm.auto.tqdm` but also sends updates to a Discord Bot.
99
+ May take a few seconds to create (`__init__`).
100
+
101
+ - create a discord bot (not public, no requirement of OAuth2 code
102
+ grant, only send message permissions) & invite it to a channel:
103
+ <https://discordpy.readthedocs.io/en/latest/discord.html>
104
+ - copy the bot `{token}` & `{channel_id}` and paste below
105
+
106
+ >>> from tqdm.contrib.discord import tqdm, trange
107
+ >>> for i in tqdm(iterable, token='{token}', channel_id='{channel_id}'):
108
+ ... ...
109
+ """
110
+ @envwrap("tqdm", "discord", is_method=True)
111
+ def __init__(self, *args, token=None, channel_id=None, **kwargs):
112
+ """
113
+ Parameters
114
+ ----------
115
+ token : str, required. Discord bot token
116
+ [default: ${TQDM_DISCORD_TOKEN}].
117
+ channel_id : int, required. Discord channel ID
118
+ [default: ${TQDM_DISCORD_CHANNEL_ID}].
119
+
120
+ See `tqdm.auto.tqdm.__init__` for other parameters.
121
+ """
122
+ if not kwargs.get('disable'):
123
+ kwargs = kwargs.copy()
124
+ self.dio = DiscordIO(token, channel_id)
125
+ super().__init__(*args, **kwargs)
126
+
127
+ def display(self, **kwargs): # pylint: disable=arguments-differ
128
+ super().display(**kwargs)
129
+ fmt = self.format_dict
130
+ if fmt.get('bar_format', None):
131
+ fmt['bar_format'] = fmt['bar_format'].replace(
132
+ '<bar/>', '{bar:10u}').replace('{bar}', '{bar:10u}')
133
+ self.dio.write(self.format_meter(**fmt))
134
+
135
+ def clear(self, *args, **kwargs):
136
+ super().clear(*args, **kwargs)
137
+ if not self.disable:
138
+ self.dio.write("")
139
+
140
+ def close(self):
141
+ if self.disable:
142
+ return
143
+ super().close()
144
+ if not (self.leave or (self.leave is None and self.pos == 0)):
145
+ self.dio.delete()
146
+
147
+
148
+ def tdrange(*args, **kwargs):
149
+ """Shortcut for `tqdm.contrib.discord.tqdm(range(*args), **kwargs)`."""
150
+ return tqdm_discord(range(*args), **kwargs)
151
+
152
+
153
+ # Aliases
154
+ tqdm = tqdm_discord
155
+ trange = tdrange
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/contrib/itertools.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Thin wrappers around `itertools`.
3
+ """
4
+ import itertools
5
+ import math
6
+
7
+ from ..auto import tqdm as tqdm_auto
8
+
9
+ __author__ = {"github.com/": ["casperdcl"]}
10
+ __all__ = [
11
+ 'chain', 'product', 'permutations', 'combinations', 'combinations_with_replacement', 'batched']
12
+
13
+
14
+ def chain(*iterables, total=None, tqdm_class=tqdm_auto, **kwargs):
15
+ """Equivalent of `itertools.chain`."""
16
+ if total is None:
17
+ try:
18
+ total = sum(map(len, iterables))
19
+ except (TypeError, AttributeError):
20
+ pass
21
+ return tqdm_class(itertools.chain(*iterables), total=total, **kwargs)
22
+
23
+
24
+ def product(*iterables, repeat=1, total=None, tqdm_class=tqdm_auto, **kwargs):
25
+ """Equivalent of `itertools.product`."""
26
+ if total is None:
27
+ try:
28
+ lens = list(map(len, iterables))
29
+ except (TypeError, AttributeError):
30
+ pass
31
+ else:
32
+ total = math.prod(lens) ** repeat
33
+ yield from tqdm_class(itertools.product(*iterables, repeat=repeat), total=total, **kwargs)
34
+
35
+
36
+ def permutations(iterable, r=None, total=None, tqdm_class=tqdm_auto, **kwargs):
37
+ """Equivalent of `itertools.permutations`."""
38
+ if total is None:
39
+ try:
40
+ n = len(iterable)
41
+ except (TypeError, AttributeError):
42
+ pass
43
+ else:
44
+ r = n if r is None else r
45
+ if r > n:
46
+ total = 0
47
+ else:
48
+ total = math.perm(n, r)
49
+ return tqdm_class(itertools.permutations(iterable, r), total=total, **kwargs)
50
+
51
+
52
+ def combinations(iterable, r, total=None, tqdm_class=tqdm_auto, **kwargs):
53
+ """Equivalent of `itertools.combinations`."""
54
+ if total is None:
55
+ try:
56
+ n = len(iterable)
57
+ except (TypeError, AttributeError):
58
+ pass
59
+ else:
60
+ if r > n:
61
+ total = 0
62
+ else:
63
+ total = math.comb(n, r)
64
+ return tqdm_class(itertools.combinations(iterable, r), total=total, **kwargs)
65
+
66
+
67
+ def combinations_with_replacement(iterable, r, total=None, tqdm_class=tqdm_auto, **kwargs):
68
+ """Equivalent of `itertools.combinations_with_replacement`."""
69
+ if total is None:
70
+ try:
71
+ n = len(iterable)
72
+ except (TypeError, AttributeError):
73
+ pass
74
+ else:
75
+ total = 1
76
+ for i in range(n+r-1, n-1, -1):
77
+ total *= i
78
+ for i in range(1, r+1):
79
+ total //= i
80
+ return tqdm_class(itertools.combinations_with_replacement(iterable, r), total=total, **kwargs)
81
+
82
+
83
+ def batched(iterable, n, total=None, tqdm_class=tqdm_auto, **kwargs):
84
+ """Equivalent of `itertools.batched`."""
85
+ if total is None:
86
+ try:
87
+ total = len(iterable)
88
+ except (TypeError, AttributeError):
89
+ pass
90
+ return tqdm_class(itertools.batched(iterable, n), unit_scale=n,
91
+ total=(total+n-1) // n if total is not None else None,
92
+ **kwargs)
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/contrib/logging.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helper functionality for interoperability with stdlib `logging`.
3
+ """
4
+ import logging
5
+ import sys
6
+ from contextlib import contextmanager
7
+
8
+ try:
9
+ from typing import Iterator, List, Optional, Type # noqa: F401, pylint: disable=unused-import
10
+ except ImportError:
11
+ pass
12
+
13
+ from ..std import tqdm as std_tqdm
14
+
15
+
16
+ class _TqdmLoggingHandler(logging.StreamHandler):
17
+ def __init__(
18
+ self,
19
+ tqdm_class=std_tqdm # type: Type[std_tqdm]
20
+ ):
21
+ super().__init__()
22
+ self.tqdm_class = tqdm_class
23
+
24
+ def emit(self, record):
25
+ try:
26
+ msg = self.format(record)
27
+ self.tqdm_class.write(msg, file=self.stream)
28
+ self.flush()
29
+ except (KeyboardInterrupt, SystemExit):
30
+ raise
31
+ except: # noqa pylint: disable=bare-except
32
+ self.handleError(record)
33
+
34
+
35
+ def _is_console_logging_handler(handler):
36
+ return (isinstance(handler, logging.StreamHandler)
37
+ and handler.stream in {sys.stdout, sys.stderr})
38
+
39
+
40
+ def _get_first_found_console_logging_handler(handlers):
41
+ for handler in handlers:
42
+ if _is_console_logging_handler(handler):
43
+ return handler
44
+
45
+
46
+ @contextmanager
47
+ def logging_redirect_tqdm(
48
+ loggers=None, # type: Optional[List[logging.Logger]],
49
+ tqdm_class=std_tqdm # type: Type[std_tqdm]
50
+ ):
51
+ # type: (...) -> Iterator[None]
52
+ """
53
+ Context manager redirecting console logging to `tqdm.write()`, leaving
54
+ other logging handlers (e.g. log files) unaffected.
55
+
56
+ Parameters
57
+ ----------
58
+ loggers : list, optional
59
+ Which handlers to redirect (default: [logging.root]).
60
+ tqdm_class : optional
61
+
62
+ Example
63
+ -------
64
+ ```python
65
+ import logging
66
+ from tqdm import trange
67
+ from tqdm.contrib.logging import logging_redirect_tqdm
68
+
69
+ LOG = logging.getLogger(__name__)
70
+
71
+ if __name__ == '__main__':
72
+ logging.basicConfig(level=logging.INFO)
73
+ with logging_redirect_tqdm():
74
+ for i in trange(9):
75
+ if i == 4:
76
+ LOG.info("console logging redirected to `tqdm.write()`")
77
+ # logging restored
78
+ ```
79
+ """
80
+ if loggers is None:
81
+ loggers = [logging.root]
82
+ original_handlers_list = [logger.handlers for logger in loggers]
83
+ try:
84
+ for logger in loggers:
85
+ tqdm_handler = _TqdmLoggingHandler(tqdm_class)
86
+ orig_handler = _get_first_found_console_logging_handler(logger.handlers)
87
+ if orig_handler is not None:
88
+ tqdm_handler.setFormatter(orig_handler.formatter)
89
+ tqdm_handler.stream = orig_handler.stream
90
+ for log_filter in orig_handler.filters:
91
+ tqdm_handler.addFilter(log_filter)
92
+ logger.handlers = [
93
+ handler for handler in logger.handlers
94
+ if not _is_console_logging_handler(handler)] + [tqdm_handler]
95
+ yield
96
+ finally:
97
+ for logger, original_handlers in zip(loggers, original_handlers_list):
98
+ logger.handlers = original_handlers
99
+
100
+
101
+ @contextmanager
102
+ def tqdm_logging_redirect(
103
+ *args,
104
+ # loggers=None, # type: Optional[List[logging.Logger]]
105
+ # tqdm=None, # type: Optional[Type[tqdm.tqdm]]
106
+ **kwargs
107
+ ):
108
+ # type: (...) -> Iterator[None]
109
+ """
110
+ Convenience shortcut for:
111
+ ```python
112
+ with tqdm_class(*args, **tqdm_kwargs) as pbar:
113
+ with logging_redirect_tqdm(loggers=loggers, tqdm_class=tqdm_class):
114
+ yield pbar
115
+ ```
116
+
117
+ Parameters
118
+ ----------
119
+ tqdm_class : optional, (default: tqdm.std.tqdm).
120
+ loggers : optional, list.
121
+ **tqdm_kwargs : passed to `tqdm_class`.
122
+ """
123
+ tqdm_kwargs = kwargs.copy()
124
+ loggers = tqdm_kwargs.pop('loggers', None)
125
+ tqdm_class = tqdm_kwargs.pop('tqdm_class', std_tqdm)
126
+ with tqdm_class(*args, **tqdm_kwargs) as pbar:
127
+ with logging_redirect_tqdm(loggers=loggers, tqdm_class=tqdm_class):
128
+ yield pbar
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/contrib/slack.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Sends updates to a Slack app.
3
+
4
+ Usage:
5
+ >>> from tqdm.contrib.slack import tqdm, trange
6
+ >>> for i in trange(10, token='{token}', channel='{channel}'):
7
+ ... ...
8
+
9
+ ![screenshot](https://tqdm.github.io/img/screenshot-slack.png)
10
+ """
11
+ import logging
12
+
13
+ try:
14
+ from slack_sdk import WebClient
15
+ except ImportError:
16
+ raise ImportError("Please `pip install slack-sdk`")
17
+
18
+ from ..auto import tqdm as tqdm_auto
19
+ from ..utils import envwrap
20
+ from .utils_worker import MonoWorker
21
+
22
+ __author__ = {"github.com/": ["0x2b3bfa0", "casperdcl"]}
23
+ __all__ = ['SlackIO', 'tqdm_slack', 'tsrange', 'tqdm', 'trange']
24
+
25
+
26
+ class SlackIO(MonoWorker):
27
+ """Non-blocking file-like IO using a Slack app."""
28
+ def __init__(self, token, channel):
29
+ """Creates a new message in the given `channel`."""
30
+ super().__init__()
31
+ self.client = WebClient(token=token)
32
+ self.text = self.__class__.__name__
33
+ try:
34
+ self.message = self.client.chat_postMessage(channel=channel, text=self.text)
35
+ except Exception as e:
36
+ tqdm_auto.write(str(e))
37
+ self.message = None
38
+
39
+ def write(self, s):
40
+ """Replaces internal `message`'s text with `s`."""
41
+ if not s:
42
+ s = "..."
43
+ s = s.replace('\r', '').strip()
44
+ if s == self.text:
45
+ return # skip duplicate message
46
+ message = self.message
47
+ if message is None:
48
+ return
49
+ self.text = s
50
+ try:
51
+ future = self.submit(self.client.chat_update, channel=message['channel'],
52
+ ts=message['ts'], text='`' + s + '`')
53
+ except Exception as e:
54
+ tqdm_auto.write(str(e))
55
+ else:
56
+ return future
57
+
58
+
59
+ class tqdm_slack(tqdm_auto): # pylint: disable=inconsistent-mro
60
+ """
61
+ Standard `tqdm.auto.tqdm` but also sends updates to a Slack app.
62
+ May take a few seconds to create (`__init__`).
63
+
64
+ - create a Slack app with the `chat:write` scope & invite it to a
65
+ channel: <https://api.slack.com/authentication/basics>
66
+ - copy the bot `{token}` & `{channel}` and paste below
67
+ >>> from tqdm.contrib.slack import tqdm, trange
68
+ >>> for i in tqdm(iterable, token='{token}', channel='{channel}'):
69
+ ... ...
70
+ """
71
+ @envwrap("tqdm", "slack", is_method=True)
72
+ def __init__(self, *args, token=None, channel=None, **kwargs):
73
+ """
74
+ Parameters
75
+ ----------
76
+ token : str, required. Slack token
77
+ [default: ${TQDM_SLACK_TOKEN}].
78
+ channel : int, required. Slack channel
79
+ [default: ${TQDM_SLACK_CHANNEL}].
80
+ mininterval : float, optional.
81
+ Minimum of [default: 1.5] to avoid rate limit.
82
+
83
+ See `tqdm.auto.tqdm.__init__` for other parameters.
84
+ """
85
+ if not kwargs.get('disable'):
86
+ kwargs = kwargs.copy()
87
+ logging.getLogger("HTTPClient").setLevel(logging.WARNING)
88
+ self.sio = SlackIO(token, channel)
89
+ kwargs['mininterval'] = max(1.5, kwargs.get('mininterval', 1.5))
90
+ super().__init__(*args, **kwargs)
91
+
92
+ def display(self, **kwargs): # pylint: disable=arguments-differ
93
+ super().display(**kwargs)
94
+ fmt = self.format_dict
95
+ if fmt.get('bar_format', None):
96
+ fmt['bar_format'] = fmt['bar_format'].replace(
97
+ '<bar/>', '`{bar:10}`').replace('{bar}', '`{bar:10u}`')
98
+ elif self.total:
99
+ fmt['bar_format'] = '{l_bar}`{bar:10}`{r_bar}'
100
+ if fmt['ascii'] is False:
101
+ fmt['ascii'] = [":black_square:", ":small_blue_diamond:", ":large_blue_diamond:",
102
+ ":large_blue_square:"]
103
+ fmt['ncols'] = 336
104
+ self.sio.write(self.format_meter(**fmt))
105
+
106
+ def clear(self, *args, **kwargs):
107
+ super().clear(*args, **kwargs)
108
+ if not self.disable:
109
+ self.sio.write("")
110
+
111
+
112
+ def tsrange(*args, **kwargs):
113
+ """Shortcut for `tqdm.contrib.slack.tqdm(range(*args), **kwargs)`."""
114
+ return tqdm_slack(range(*args), **kwargs)
115
+
116
+
117
+ # Aliases
118
+ tqdm = tqdm_slack
119
+ trange = tsrange
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/contrib/telegram.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Sends updates to a Telegram bot.
3
+
4
+ Usage:
5
+ >>> from tqdm.contrib.telegram import tqdm, trange
6
+ >>> for i in trange(10, token='{token}', chat_id='{chat_id}'):
7
+ ... ...
8
+
9
+ ![screenshot](https://tqdm.github.io/img/screenshot-telegram.gif)
10
+ """
11
+ from warnings import warn
12
+
13
+ from requests import Session
14
+
15
+ from ..auto import tqdm as tqdm_auto
16
+ from ..std import TqdmWarning
17
+ from ..utils import envwrap
18
+ from .utils_worker import MonoWorker
19
+
20
+ __author__ = {"github.com/": ["casperdcl"]}
21
+ __all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'trange']
22
+
23
+
24
+ class TelegramIO(MonoWorker):
25
+ """Non-blocking file-like IO using a Telegram Bot."""
26
+ API = 'https://api.telegram.org/bot'
27
+
28
+ def __init__(self, token, chat_id):
29
+ """Creates a new message in the given `chat_id`."""
30
+ super().__init__()
31
+ self.token = token
32
+ self.chat_id = chat_id
33
+ self.session = Session()
34
+ self.text = self.__class__.__name__
35
+ self.message_id # pylint: disable=pointless-statement
36
+
37
+ @property
38
+ def message_id(self):
39
+ if hasattr(self, '_message_id'):
40
+ return self._message_id # pylint: disable=access-member-before-definition
41
+ try:
42
+ req = self.session.post(
43
+ f'{self.API}{self.token}/sendMessage',
44
+ data={'text': f"`{self.text}`", 'chat_id': self.chat_id,
45
+ 'parse_mode': 'MarkdownV2'})
46
+ res = req.json()
47
+ req.raise_for_status()
48
+ except Exception as e:
49
+ if req.status_code == 429:
50
+ warn("Creation rate limit: try increasing `mininterval`.",
51
+ TqdmWarning, stacklevel=2)
52
+ else:
53
+ tqdm_auto.write(str(e))
54
+ else:
55
+ self._message_id = res['result']['message_id']
56
+ return self._message_id
57
+
58
+ def write(self, s):
59
+ """Replaces internal `message_id`'s text with `s`."""
60
+ if not s:
61
+ s = "..."
62
+ s = s.replace('\r', '').strip()
63
+ if s == self.text:
64
+ return # avoid duplicate message Bot error
65
+ message_id = self.message_id
66
+ if message_id is None:
67
+ return
68
+ self.text = s
69
+ try:
70
+ future = self.submit(
71
+ self.session.post, f'{self.API}{self.token}/editMessageText',
72
+ data={'text': f"`{s}`", 'chat_id': self.chat_id,
73
+ 'message_id': message_id, 'parse_mode': 'MarkdownV2'})
74
+ except Exception as e:
75
+ tqdm_auto.write(str(e))
76
+ else:
77
+ return future
78
+
79
+ def delete(self):
80
+ """Deletes internal `message_id`."""
81
+ try:
82
+ future = self.submit(
83
+ self.session.post, '{self.API}{self.token}/deleteMessage',
84
+ data={'chat_id': self.chat_id, 'message_id': self.message_id})
85
+ except Exception as e:
86
+ tqdm_auto.write(str(e))
87
+ else:
88
+ return future
89
+
90
+
91
+ class tqdm_telegram(tqdm_auto): # pylint: disable=inconsistent-mro
92
+ """
93
+ Standard `tqdm.auto.tqdm` but also sends updates to a Telegram Bot.
94
+ May take a few seconds to create (`__init__`).
95
+
96
+ - create a bot <https://core.telegram.org/bots#6-botfather>
97
+ - copy its `{token}`
98
+ - add the bot to a chat and send it a message such as `/start`
99
+ - go to <https://api.telegram.org/bot`{token}`/getUpdates> to find out
100
+ the `{chat_id}`
101
+ - paste the `{token}` & `{chat_id}` below
102
+
103
+ >>> from tqdm.contrib.telegram import tqdm, trange
104
+ >>> for i in tqdm(iterable, token='{token}', chat_id='{chat_id}'):
105
+ ... ...
106
+ """
107
+ @envwrap("tqdm", "telegram", is_method=True)
108
+ def __init__(self, *args, token=None, chat_id=None, **kwargs):
109
+ """
110
+ Parameters
111
+ ----------
112
+ token : str, required. Telegram token
113
+ [default: ${TQDM_TELEGRAM_TOKEN}].
114
+ chat_id : str, required. Telegram chat ID
115
+ [default: ${TQDM_TELEGRAM_CHAT_ID}].
116
+
117
+ See `tqdm.auto.tqdm.__init__` for other parameters.
118
+ """
119
+ if not kwargs.get('disable'):
120
+ kwargs = kwargs.copy()
121
+ self.tgio = TelegramIO(token, chat_id)
122
+ super().__init__(*args, **kwargs)
123
+
124
+ def display(self, **kwargs): # pylint: disable=arguments-differ
125
+ super().display(**kwargs)
126
+ fmt = self.format_dict
127
+ if fmt.get('bar_format', None):
128
+ fmt['bar_format'] = fmt['bar_format'].replace(
129
+ '<bar/>', '{bar:10u}').replace('{bar}', '{bar:10u}')
130
+ self.tgio.write(self.format_meter(**fmt))
131
+
132
+ def clear(self, *args, **kwargs):
133
+ super().clear(*args, **kwargs)
134
+ if not self.disable:
135
+ self.tgio.write("")
136
+
137
+ def close(self):
138
+ if self.disable:
139
+ return
140
+ super().close()
141
+ if not (self.leave or (self.leave is None and self.pos == 0)):
142
+ self.tgio.delete()
143
+
144
+
145
+ def ttgrange(*args, **kwargs):
146
+ """Shortcut for `tqdm.contrib.telegram.tqdm(range(*args), **kwargs)`."""
147
+ return tqdm_telegram(range(*args), **kwargs)
148
+
149
+
150
+ # Aliases
151
+ tqdm = tqdm_telegram
152
+ trange = ttgrange
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/contrib/utils_worker.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ IO/concurrency helpers for `tqdm.contrib`.
3
+ """
4
+ from collections import deque
5
+ from concurrent.futures import ThreadPoolExecutor
6
+
7
+ from ..auto import tqdm as tqdm_auto
8
+
9
+ __author__ = {"github.com/": ["casperdcl"]}
10
+ __all__ = ['MonoWorker']
11
+
12
+
13
+ class MonoWorker:
14
+ """
15
+ Supports one running task and one waiting task.
16
+ The waiting task is the most recent submitted (others are discarded).
17
+ """
18
+ def __init__(self):
19
+ self.pool = ThreadPoolExecutor(max_workers=1)
20
+ self.futures = deque([], 2)
21
+
22
+ def submit(self, func, *args, **kwargs):
23
+ """`func(*args, **kwargs)` may replace currently waiting task."""
24
+ futures = self.futures
25
+ if len(futures) == futures.maxlen:
26
+ running = futures.popleft()
27
+ if not running.done():
28
+ if len(futures): # clear waiting
29
+ waiting = futures.pop()
30
+ waiting.cancel()
31
+ futures.appendleft(running) # re-insert running
32
+ try:
33
+ waiting = self.pool.submit(func, *args, **kwargs)
34
+ except Exception as e:
35
+ tqdm_auto.write(str(e))
36
+ else:
37
+ futures.append(waiting)
38
+ return waiting
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/dask.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import partial
2
+
3
+ from dask.callbacks import Callback
4
+
5
+ from .auto import tqdm as tqdm_auto
6
+
7
+ __author__ = {"github.com/": ["casperdcl"]}
8
+ __all__ = ['TqdmCallback']
9
+
10
+
11
+ class TqdmCallback(Callback):
12
+ """Dask callback for task progress."""
13
+ def __init__(self, start=None, pretask=None, tqdm_class=tqdm_auto,
14
+ **tqdm_kwargs):
15
+ """
16
+ Parameters
17
+ ----------
18
+ tqdm_class : optional
19
+ `tqdm` class to use for bars [default: `tqdm.auto.tqdm`].
20
+ tqdm_kwargs : optional
21
+ Any other arguments used for all bars.
22
+ """
23
+ super().__init__(start=start, pretask=pretask)
24
+ if tqdm_kwargs:
25
+ tqdm_class = partial(tqdm_class, **tqdm_kwargs)
26
+ self.tqdm_class = tqdm_class
27
+
28
+ def _start_state(self, _, state):
29
+ self.pbar = self.tqdm_class(total=sum(
30
+ len(state[k]) for k in ['ready', 'waiting', 'running', 'finished']))
31
+
32
+ def _posttask(self, *_, **__):
33
+ self.pbar.update()
34
+
35
+ def _finish(self, *_, **__):
36
+ self.pbar.close()
37
+
38
+ def display(self):
39
+ """Displays in the current cell in Notebooks."""
40
+ container = getattr(self.bar, 'container', None)
41
+ if container is None:
42
+ return
43
+ from .notebook import display
44
+ display(container)
pace_revision_2/.venv-pace/lib/python3.11/site-packages/tqdm/gui.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Matplotlib GUI progress bar decorator for iterators.
3
+
4
+ Usage:
5
+ >>> from tqdm.gui import trange, tqdm
6
+ >>> for i in trange(10):
7
+ ... ...
8
+ """
9
+ # future division is important to divide integers and get as
10
+ # a result precise floating numbers (instead of truncated int)
11
+ import re
12
+ from warnings import warn
13
+
14
+ # to inherit from the tqdm class
15
+ from .std import TqdmExperimentalWarning
16
+ from .std import tqdm as std_tqdm
17
+
18
+ # import compatibility functions and utilities
19
+
20
+ __author__ = {"github.com/": ["casperdcl", "lrq3000"]}
21
+ __all__ = ['tqdm_gui', 'tgrange', 'tqdm', 'trange']
22
+
23
+
24
+ class tqdm_gui(std_tqdm): # pragma: no cover
25
+ """Experimental Matplotlib GUI version of tqdm!"""
26
+ # TODO: @classmethod: write() on GUI?
27
+ def __init__(self, *args, **kwargs):
28
+ from collections import deque
29
+
30
+ import matplotlib as mpl
31
+ import matplotlib.pyplot as plt
32
+ kwargs = kwargs.copy()
33
+ kwargs['gui'] = True
34
+ colour = kwargs.pop('colour', 'g')
35
+ super().__init__(*args, **kwargs)
36
+
37
+ if self.disable:
38
+ return
39
+
40
+ warn("GUI is experimental/alpha", TqdmExperimentalWarning, stacklevel=2)
41
+ self.mpl = mpl
42
+ self.plt = plt
43
+
44
+ # Remember if external environment uses toolbars
45
+ self.toolbar = self.mpl.rcParams['toolbar']
46
+ self.mpl.rcParams['toolbar'] = 'None'
47
+
48
+ self.mininterval = max(self.mininterval, 0.5)
49
+ self.fig, ax = plt.subplots(figsize=(9, 2.2))
50
+ # self.fig.subplots_adjust(bottom=0.2)
51
+ total = self.__len__() # avoids TypeError on None #971
52
+ if total is not None:
53
+ self.xdata = []
54
+ self.ydata = []
55
+ self.zdata = []
56
+ else:
57
+ self.xdata = deque([])
58
+ self.ydata = deque([])
59
+ self.zdata = deque([])
60
+ self.line1, = ax.plot(self.xdata, self.ydata, color='b')
61
+ self.line2, = ax.plot(self.xdata, self.zdata, color='k')
62
+ ax.set_ylim(0, 0.001)
63
+ if total is not None:
64
+ ax.set_xlim(0, 100)
65
+ ax.set_xlabel("percent")
66
+ self.fig.legend((self.line1, self.line2), ("cur", "est"),
67
+ loc='center right')
68
+ # progress bar
69
+ self.hspan = plt.axhspan(0, 0.001, xmin=0, xmax=0, color=colour)
70
+ else:
71
+ # ax.set_xlim(-60, 0)
72
+ ax.set_xlim(0, 60)
73
+ ax.invert_xaxis()
74
+ ax.set_xlabel("seconds")
75
+ ax.legend(("cur", "est"), loc='lower left')
76
+ ax.grid()
77
+ # ax.set_xlabel('seconds')
78
+ ax.set_ylabel((self.unit if self.unit else "it") + "/s")
79
+ if self.unit_scale:
80
+ plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
81
+ ax.yaxis.get_offset_text().set_x(-0.15)
82
+
83
+ # Remember if external environment is interactive
84
+ self.wasion = plt.isinteractive()
85
+ plt.ion()
86
+ self.ax = ax
87
+
88
+ def close(self):
89
+ if self.disable:
90
+ return
91
+
92
+ self.disable = True
93
+
94
+ with self.get_lock():
95
+ self._instances.remove(self)
96
+
97
+ # Restore toolbars
98
+ self.mpl.rcParams['toolbar'] = self.toolbar
99
+ # Return to non-interactive mode
100
+ if not self.wasion:
101
+ self.plt.ioff()
102
+ if self.leave:
103
+ self.display()
104
+ else:
105
+ self.plt.close(self.fig)
106
+
107
+ def clear(self, *_, **__):
108
+ pass
109
+
110
+ def display(self, *_, **__):
111
+ n = self.n
112
+ cur_t = self._time()
113
+ elapsed = cur_t - self.start_t
114
+ delta_it = n - self.last_print_n
115
+ delta_t = cur_t - self.last_print_t
116
+
117
+ # Inline due to multiple calls
118
+ total = self.total
119
+ xdata = self.xdata
120
+ ydata = self.ydata
121
+ zdata = self.zdata
122
+ ax = self.ax
123
+ line1 = self.line1
124
+ line2 = self.line2
125
+ hspan = getattr(self, 'hspan', None)
126
+ # instantaneous rate
127
+ y = delta_it / delta_t
128
+ # overall rate
129
+ z = n / elapsed
130
+ # update line data
131
+ xdata.append(n * 100.0 / total if total else cur_t)
132
+ ydata.append(y)
133
+ zdata.append(z)
134
+
135
+ # Discard old values
136
+ # xmin, xmax = ax.get_xlim()
137
+ # if (not total) and elapsed > xmin * 1.1:
138
+ if (not total) and elapsed > 66:
139
+ xdata.popleft()
140
+ ydata.popleft()
141
+ zdata.popleft()
142
+
143
+ ymin, ymax = ax.get_ylim()
144
+ if y > ymax or z > ymax:
145
+ ymax = 1.1 * y
146
+ ax.set_ylim(ymin, ymax)
147
+ ax.figure.canvas.draw()
148
+
149
+ if total:
150
+ line1.set_data(xdata, ydata)
151
+ line2.set_data(xdata, zdata)
152
+ if hspan:
153
+ hspan.set_xy((0, ymin))
154
+ hspan.set_height(ymax - ymin)
155
+ hspan.set_width(n / total)
156
+ else:
157
+ t_ago = [cur_t - i for i in xdata]
158
+ line1.set_data(t_ago, ydata)
159
+ line2.set_data(t_ago, zdata)
160
+
161
+ d = self.format_dict
162
+ # remove {bar}
163
+ d['bar_format'] = (d['bar_format'] or "{l_bar}<bar/>{r_bar}").replace(
164
+ "{bar}", "<bar/>")
165
+ msg = self.format_meter(**d)
166
+ if '<bar/>' in msg:
167
+ msg = "".join(re.split(r'\|?<bar/>\|?', msg, maxsplit=1))
168
+ ax.set_title(msg, fontname="DejaVu Sans Mono", fontsize=11)
169
+ self.plt.pause(1e-9)
170
+
171
+
172
+ def tgrange(*args, **kwargs):
173
+ """Shortcut for `tqdm.gui.tqdm(range(*args), **kwargs)`."""
174
+ return tqdm_gui(range(*args), **kwargs)
175
+
176
+
177
+ # Aliases
178
+ tqdm = tqdm_gui
179
+ trange = tgrange