s42chen commited on
Commit
efac223
·
verified ·
1 Parent(s): 699370e

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. shared/package-files/15/15541179440b32e8eb9017b1e775ba2e9ec12212a94f0ac35f5861df9bdb2c32/fix_long.cpython-311.pyc +0 -0
  2. shared/package-files/15/1558519863f5b6592e3a1a06c48350091177964a3bce9ffdafecaa850a6727c0/decomposition_registry.h +33 -0
  3. shared/package-files/15/1592d82c529ad42a91a8e133218de9ffb1ff4645c44f3dc781c1bfba0337dcb9/mkldnn_max_pool2d_backward_native.h +22 -0
  4. shared/package-files/15/15a211104c079d99cb1ed239538d21100f25b36c50cc61d68d176f73425e3b31/cauchy_meta_dispatch.h +23 -0
  5. shared/package-files/15/15b8b8bbe496edda37e7ed2da9fb6979db8b1ca23d64b86644800f6d84e88f56/_scaled_dot_product_flash_attention_for_cpu_backward.h +31 -0
  6. shared/package-files/41/4100980835c5ee046cf306bac5d774f3ff48cd78da81285ffa41f1c5dcc495cb/_slow_conv2d_forward_ops.h +40 -0
  7. shared/package-files/41/410c8b95359379ed124d7d95c9f00cd9c54bf84fd9ab9281d6aded055f60d9f3/_foreach_neg_compositeexplicitautograd_dispatch.h +26 -0
  8. shared/package-files/41/410dd79bac388e0435dbaae564c91d4ad0337b1125d2bf34cfeb99f382b390d2/_dtypes.cpython-311.pyc +0 -0
  9. shared/package-files/41/4112f99abcf2a1a76b661a10711cfc6fbf19509e3c34b5e19ae61ad630a6430f/_registrations.py +221 -0
  10. shared/package-files/41/41156e3b32edabf6cfd74c2cfd9e112b093803a883defa1b63650a1655396743/style.cpython-311.pyc +0 -0
  11. shared/package-files/41/4118982954345ffd2515cea40c4cfba04ef6e84c8ea43044c4291f6048877a2e/test_contains.cpython-311.pyc +0 -0
  12. shared/package-files/41/411edb7f93c2bb27df248043647e5de9d664b2afbda3e1160d725cad5c6b435e/_foreach_zero_compositeexplicitautograd_dispatch.h +26 -0
  13. shared/package-files/41/4124cc45bf65ec8f669ef4f5ffc29736a2cee3cc166961201bdedb0e3121d627/cuda_fp8.h +475 -0
  14. shared/package-files/41/412883b21ac7fc219aa23959367199aebd77be61667c879684842bc4c5c6bbe8/dimensions.cpython-311.pyc +0 -0
  15. shared/package-files/41/412daf67230897b080ad244359767c385637fe343e05031676c8674a7624ce88/traversal.cpython-311.pyc +0 -0
  16. shared/package-files/41/41392d016170860c41dbfd83f6a34a8338b16e42c7903b474e9daa8c0b682ca1/test_core.cpython-311.pyc +0 -0
  17. shared/package-files/41/413a78674c3ded3d643aeecb9ea36e5edd233c0be3e6fcb057e70039105e04df/test_complexes.cpython-311.pyc +0 -0
  18. shared/package-files/41/41401633a1f8e5806477b7d7ea35d73b78feb5f55a1e1cf16d79fb3a74a6d04b/codeprinter.py +1039 -0
  19. shared/package-files/41/414ca861a10a75b05dddccaeaab88fbbe9e17639604f1b418166bd463e80fa93/_upsample_nearest_exact3d_cpu_dispatch.h +28 -0
  20. shared/package-files/41/414ec74c1ee8ff7eeaeeeac2c6f48b6171fa9a596fd2c52bd5ada631a035e60d/script-with-bom.cpython-311.pyc +0 -0
  21. shared/package-files/41/414ed911448d0874dd3c1604a54d32949a9c9d2da2a19fff24fb3b349e91f07e/test_public_api.cpython-311.pyc +0 -0
  22. shared/package-files/41/41539ec016af9995bc45a8df71481f41d1d3d649f39bdd64e8be3eb0b888a2a2/test_api.cpython-311.pyc +0 -0
  23. shared/package-files/41/4153c68e57baad432b97f121708f3447dfe5cdbdd95cac85c2b2008f3bd1d49d/extending_distributions.cpython-311.pyc +0 -0
  24. shared/package-files/41/415703c6edaaa239a93881cac0e4fc8fdfb958fb351561623fb2f2a553c0ff88/_analysis.py +242 -0
  25. shared/package-files/41/41572ac50cf96b04496e676d8a6708898bb8e752e06dad34ed4c50c5d8f1fe40/_casefix.py +106 -0
  26. shared/package-files/41/41572cc508b286773cb8b3c20161918a6971c4138e633e6cfe3f342c15337d8b/quantized_batch_norm.h +40 -0
  27. shared/package-files/41/415b0de31cdcfae837bcf8ea4fbb056c6a0871e322b9362b62d4b84d8f79fb92/arrayop.cpython-311.pyc +0 -0
  28. shared/package-files/41/415cdc1afe4e2e8c659620d48843cc32c11e42174b9c4d50bad3fc71a3b9083f/random.py +181 -0
  29. shared/package-files/41/416494ee611cf9890b4697912f2e99b7daf78fcc011205656ecd243a29652a04/subclass_parametrization.cpython-311.pyc +0 -0
  30. shared/package-files/41/416888499fadfed2fe45d7ac4c27bf11076550cd1e7d6be99f8e6b90c01a1ddb/choose_qparams_optimized_native.h +21 -0
  31. shared/package-files/41/416cda72c316ec5b646ac62fb19f56a9113106368caacc474070f9b58b190450/conv_relu.py +8 -0
  32. shared/package-files/41/41703b13df5086b125aed6ea643965701e86f26522fa04f520191c0b5c0a5010/_arrow_string_mixins.cpython-311.pyc +0 -0
  33. shared/package-files/41/41733bee0b435a924f09b0d6fd085c0159f2fde59c54b11bb44e211a4d8244a2/_functional_assert_scalar_ops.h +29 -0
  34. shared/package-files/41/4174e71f63cce4b8834669601c92888e99b2e00092b840a8f8ee8720b807f293/ReduceOps.h +20 -0
  35. shared/package-files/41/41760d83887db0c5612d20cec9a893908bff91f7ca948e1858855a8639ab8354/test_solvers.cpython-311.pyc +0 -0
  36. shared/package-files/41/417696b7aa221ecfbc25e2ab9d43ebea88d33baf31d91d1bca393974a5917a91/agent_utils.h +42 -0
  37. shared/package-files/41/417826f08df4a690975d36ec53ad6ecbfe7b3dbf9ee4da572c94e257ee27a5aa/test_matching.cpython-311.pyc +0 -0
  38. shared/package-files/41/41874553df0d7b5da2b206d102f59ccf6c29bdee40e70fdc15f2cac31525d000/test_parenmatch.cpython-311.pyc +0 -0
  39. shared/package-files/41/418a9296e5619b1abf0406a010a05be9e248b1e14503078c8e9b8b80d3cc5162/test_codegen_julia.py +620 -0
  40. shared/package-files/41/418c1561a3f8b5203203ac455f5bd0f9f450e1f7cfc32ebce2a3dfa57ae33d0d/orthogonal.cpython-311.pyc +0 -0
  41. shared/package-files/41/4193c4708f649ac3613873f70ffdfd9e9a5ad3c53d9afdda1d0b8e4d2f8e43ce/upsample_linear1d_meta.h +27 -0
  42. shared/package-files/41/419441196543bf6adff43168a0bdf1a8c1238973d92e28826d9b52b56569b47d/native_layer_norm_compositeexplicitautograd_dispatch.h +28 -0
  43. shared/package-files/41/41952fafbed3c491e37604153698a102ea20960d608551ce4c314e55727da5c1/test_ipython.py +278 -0
  44. shared/package-files/41/4195e10347eb055351b006ab1033998a32305786428348d4dbf88696e71c1f38/test_common.cpython-311.pyc +0 -0
  45. shared/package-files/41/419611038ad585a4dc27bd75d052763344c82ad45da3cf35c35284c4dd0b0a78/windows_events.py +952 -0
  46. shared/package-files/41/4196267074d3418142057b3fd8ee01f70773765821a3b706997853761e364686/_cast_Int_ops.h +29 -0
  47. shared/package-files/41/41999bc58f9f7203eeb1e60b9ca54316ca07ea6e7b0a8b2fcb85bb9788c8a96c/plotgrid.py +188 -0
  48. shared/package-files/41/419e2f2664becb546976b555a200a0ec7b3dea4292a597c16ccfe6b9a2e18dd7/device_op_overrides.cpython-311.pyc +0 -0
  49. shared/package-files/41/41a595b9f946c505054e855c5952336471bf6fc566e09246ea605954635ab0ad/test_vlen_array.py +97 -0
  50. shared/package-files/41/41a607bad835178db0de3bce283f20896cb10ead4654172cf8aa58c6672ad70b/binary_cross_entropy.h +40 -0
shared/package-files/15/15541179440b32e8eb9017b1e775ba2e9ec12212a94f0ac35f5861df9bdb2c32/fix_long.cpython-311.pyc ADDED
Binary file (1.23 kB). View file
 
shared/package-files/15/1558519863f5b6592e3a1a06c48350091177964a3bce9ffdafecaa850a6727c0/decomposition_registry.h ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // This file is temporary until native_functions.yaml and derivatives.yaml are
3
+ // merged. Ideally this should all go into native_functions.yaml
4
+
5
+ #include <torch/csrc/Export.h>
6
+ #include <torch/csrc/jit/ir/ir.h>
7
+
8
+ namespace torch::jit {
9
+
10
+ TORCH_API std::optional<std::shared_ptr<Graph>> GetDecomposition(
11
+ const FunctionSchema& schema);
12
+
13
+ TORCH_API void RegisterDecomposition(
14
+ const FunctionSchema& schema,
15
+ std::shared_ptr<Graph> g);
16
+
17
+ TORCH_API void RunDecompositions(std::shared_ptr<Graph> g);
18
+
19
+ TORCH_API std::optional<GraphFunction*> GetDecompositionFunction(
20
+ const FunctionSchema& schema);
21
+
22
+ // For invocation in C++, recommended is to assign to static local variable
23
+ TORCH_API Function* GetDecompositionExecutor(const char* schema_literal);
24
+
25
+ TORCH_API Function* GetDecompositionExecutor(const FunctionSchema& schema);
26
+
27
+ TORCH_API void run_jit_decomposition(
28
+ const c10::OperatorHandle& op,
29
+ torch::jit::Stack* stack);
30
+
31
+ TORCH_API bool has_jit_decomposition(const FunctionSchema& schema);
32
+
33
+ } // namespace torch::jit
shared/package-files/15/1592d82c529ad42a91a8e133218de9ffb1ff4645c44f3dc781c1bfba0337dcb9/mkldnn_max_pool2d_backward_native.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor & mkldnn_max_pool2d_backward_out(const at::Tensor & grad_output, const at::Tensor & output, const at::Tensor & input, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode, at::Tensor & out);
20
+ TORCH_API at::Tensor mkldnn_max_pool2d_backward(const at::Tensor & grad_output, const at::Tensor & output, const at::Tensor & input, at::IntArrayRef kernel_size, at::IntArrayRef stride={}, at::IntArrayRef padding=0, at::IntArrayRef dilation=1, bool ceil_mode=false);
21
+ } // namespace native
22
+ } // namespace at
shared/package-files/15/15a211104c079d99cb1ed239538d21100f25b36c50cc61d68d176f73425e3b31/cauchy_meta_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace meta {
19
+
20
+ TORCH_API at::Tensor & cauchy_(at::Tensor & self, double median=0, double sigma=1, ::std::optional<at::Generator> generator=::std::nullopt);
21
+
22
+ } // namespace meta
23
+ } // namespace at
shared/package-files/15/15b8b8bbe496edda37e7ed2da9fb6979db8b1ca23d64b86644800f6d84e88f56/_scaled_dot_product_flash_attention_for_cpu_backward.h ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+ #include <string_view>
18
+
19
+
20
+
21
+ #include <ATen/ops/_scaled_dot_product_flash_attention_for_cpu_backward_ops.h>
22
+
23
+ namespace at {
24
+
25
+
26
+ // aten::_scaled_dot_product_flash_attention_for_cpu_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor out, Tensor logsumexp, float dropout_p, bool is_causal, *, Tensor? attn_mask=None, float? scale=None) -> (Tensor grad_query, Tensor grad_key, Tensor grad_value)
27
+ inline ::std::tuple<at::Tensor,at::Tensor,at::Tensor> _scaled_dot_product_flash_attention_for_cpu_backward(const at::Tensor & grad_out, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const at::Tensor & out, const at::Tensor & logsumexp, double dropout_p, bool is_causal, const ::std::optional<at::Tensor> & attn_mask={}, ::std::optional<double> scale=::std::nullopt) {
28
+ return at::_ops::_scaled_dot_product_flash_attention_for_cpu_backward::call(grad_out, query, key, value, out, logsumexp, dropout_p, is_causal, attn_mask, scale);
29
+ }
30
+
31
+ }
shared/package-files/41/4100980835c5ee046cf306bac5d774f3ff48cd78da81285ffa41f1c5dcc495cb/_slow_conv2d_forward_ops.h ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <string_view>
6
+ #include <tuple>
7
+ #include <vector>
8
+
9
+ // Forward declarations of any types needed in the operator signatures.
10
+ // We can't directly include these classes because it will cause circular include dependencies.
11
+ // This file is included by TensorBody.h, which defines the Tensor class.
12
+ #include <ATen/core/ATen_fwd.h>
13
+
14
+ namespace at {
15
+ namespace _ops {
16
+
17
+
18
+ struct TORCH_API _slow_conv2d_forward_output {
19
+ using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, c10::SymIntArrayRef, const ::std::optional<at::Tensor> &, c10::SymIntArrayRef, c10::SymIntArrayRef, at::Tensor &);
20
+ using ptr_schema = schema*;
21
+ // See Note [static constexpr char* members for windows NVCC]
22
+ static constexpr const char* name = "aten::_slow_conv2d_forward";
23
+ static constexpr const char* overload_name = "output";
24
+ static constexpr const char* schema_str = "_slow_conv2d_forward.output(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias, SymInt[2] stride, SymInt[2] padding, *, Tensor(a!) output) -> Tensor(a!)";
25
+ static at::Tensor & call(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const ::std::optional<at::Tensor> & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, at::Tensor & output);
26
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const ::std::optional<at::Tensor> & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, at::Tensor & output);
27
+ };
28
+
29
+ struct TORCH_API _slow_conv2d_forward {
30
+ using schema = at::Tensor (const at::Tensor &, const at::Tensor &, c10::SymIntArrayRef, const ::std::optional<at::Tensor> &, c10::SymIntArrayRef, c10::SymIntArrayRef);
31
+ using ptr_schema = schema*;
32
+ // See Note [static constexpr char* members for windows NVCC]
33
+ static constexpr const char* name = "aten::_slow_conv2d_forward";
34
+ static constexpr const char* overload_name = "";
35
+ static constexpr const char* schema_str = "_slow_conv2d_forward(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias, SymInt[2] stride, SymInt[2] padding) -> Tensor";
36
+ static at::Tensor call(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const ::std::optional<at::Tensor> & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding);
37
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const ::std::optional<at::Tensor> & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding);
38
+ };
39
+
40
+ }} // namespace at::_ops
shared/package-files/41/410c8b95359379ed124d7d95c9f00cd9c54bf84fd9ab9281d6aded055f60d9f3/_foreach_neg_compositeexplicitautograd_dispatch.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API ::std::vector<at::Tensor> _foreach_neg(at::TensorList self);
21
+ TORCH_API void _foreach_neg_out(at::TensorList out, at::TensorList self);
22
+ TORCH_API void _foreach_neg_outf(at::TensorList self, at::TensorList out);
23
+ TORCH_API void _foreach_neg_(at::TensorList self);
24
+
25
+ } // namespace compositeexplicitautograd
26
+ } // namespace at
shared/package-files/41/410dd79bac388e0435dbaae564c91d4ad0337b1125d2bf34cfeb99f382b390d2/_dtypes.cpython-311.pyc ADDED
Binary file (4.37 kB). View file
 
shared/package-files/41/4112f99abcf2a1a76b661a10711cfc6fbf19509e3c34b5e19ae61ad630a6430f/_registrations.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: B950
2
+ from ._internal import register_artifact, register_log
3
+
4
+
5
+ DYNAMIC = [
6
+ "torch.fx.experimental.symbolic_shapes",
7
+ "torch.fx.experimental.sym_node",
8
+ "torch.fx.experimental.recording",
9
+ ]
10
+ DISTRIBUTED = [
11
+ "torch.distributed",
12
+ "torch._dynamo.backends.distributed",
13
+ "torch.nn.parallel.distributed",
14
+ ]
15
+
16
+ register_log(
17
+ "cache", ("torch._inductor.remote_cache", "torch._inductor.fb.remote_cache")
18
+ )
19
+ register_log("dynamo", ["torch._dynamo", *DYNAMIC])
20
+ register_log("fake_tensor", ["torch._subclasses.fake_tensor"])
21
+ register_log("aot", ["torch._functorch.aot_autograd", "torch._functorch._aot_autograd"])
22
+ register_log("autograd", "torch.autograd")
23
+ register_log("inductor", ["torch._inductor", "torch._inductor.cudagraph_trees"])
24
+
25
+ register_artifact(
26
+ "cudagraphs",
27
+ "Logs information from wrapping inductor generated code with cudagraphs.",
28
+ )
29
+
30
+ register_log("dynamic", DYNAMIC)
31
+ register_log("torch", "torch")
32
+ register_log("distributed", DISTRIBUTED)
33
+ register_log(
34
+ "c10d", ["torch.distributed.distributed_c10d", "torch.distributed.rendezvous"]
35
+ )
36
+ register_log(
37
+ "ddp", ["torch.nn.parallel.distributed", "torch._dynamo.backends.distributed"]
38
+ )
39
+ register_log("pp", ["torch.distributed.pipelining"])
40
+ register_log("fsdp", ["torch.distributed.fsdp", "torch.distributed._composable.fsdp"])
41
+ register_log("dtensor", ["torch.distributed._tensor", "torch.distributed.tensor"])
42
+ register_log("onnx", "torch.onnx")
43
+ register_log(
44
+ "export",
45
+ [
46
+ "torch._dynamo",
47
+ "torch.export",
48
+ "torch.export.dynamic_shapes",
49
+ *DYNAMIC,
50
+ "torch._export.converter",
51
+ "torch._export.non_strict_utils",
52
+ "torch._export.serde.serialize",
53
+ "torch.fx.experimental.proxy_tensor",
54
+ ],
55
+ )
56
+
57
+ register_artifact(
58
+ "guards",
59
+ "This prints the guards for every compiled Dynamo frame. It does not tell you where the guards come from.",
60
+ visible=True,
61
+ )
62
+ register_artifact("verbose_guards", "", off_by_default=True)
63
+ register_artifact(
64
+ "bytecode",
65
+ "Prints the original and modified bytecode from Dynamo. Mostly useful if you're debugging our bytecode generation in Dynamo.",
66
+ off_by_default=True,
67
+ )
68
+ register_artifact(
69
+ "graph",
70
+ "Prints the dynamo traced graph (prior to AOTDispatch) in a table. If you prefer python code use `graph_code` instead. ",
71
+ )
72
+ register_artifact("graph_code", "Like `graph`, but gives you the Python code instead.")
73
+ register_artifact(
74
+ "graph_sizes", "Prints the sizes of all FX nodes in the dynamo graph."
75
+ )
76
+ register_artifact(
77
+ "trace_source",
78
+ "As we execute bytecode, prints the file name / line number we are processing and the actual source code. Useful with `bytecode`",
79
+ )
80
+ register_artifact(
81
+ "trace_call",
82
+ "Like trace_source, but it will give you the per-expression blow-by-blow if your Python is recent enough.",
83
+ )
84
+ register_artifact(
85
+ "trace_bytecode",
86
+ "As we trace bytecode, prints the instruction and the current stack.",
87
+ )
88
+ register_artifact(
89
+ "aot_graphs",
90
+ "Prints the FX forward and backward graph generated by AOTDispatch, after partitioning. Useful to understand what's being given to Inductor",
91
+ visible=True,
92
+ )
93
+ register_artifact(
94
+ "aot_joint_graph",
95
+ "Print FX joint graph from AOTAutograd, prior to partitioning. Useful for debugging partitioning",
96
+ )
97
+ register_artifact(
98
+ "aot_graphs_effects",
99
+ "Prints the FX forward and backward graph generated by AOTDispatch, useful for debugging effects processing.",
100
+ visible=True,
101
+ )
102
+ register_artifact(
103
+ "pre_grad_graphs",
104
+ "Prints the FX graph before inductor pre grad passes. Useful to understand what's being given to Inductor before grad passes",
105
+ )
106
+ register_artifact(
107
+ "post_grad_graphs",
108
+ "Prints the FX graph generated by post grad passes. Useful to understand what's being given to Inductor after post grad passes",
109
+ )
110
+ register_artifact(
111
+ "ir_pre_fusion",
112
+ "Prints the IR before inductor fusion passes.",
113
+ off_by_default=True,
114
+ )
115
+ register_artifact(
116
+ "ir_post_fusion",
117
+ "Prints the IR after inductor fusion passes.",
118
+ off_by_default=True,
119
+ )
120
+ register_artifact(
121
+ "compiled_autograd",
122
+ "Prints various logs in compiled_autograd, including but not limited to the graphs. Useful for debugging compiled_autograd.",
123
+ visible=True,
124
+ )
125
+ register_artifact(
126
+ "compiled_autograd_verbose",
127
+ "Will affect performance. Prints compiled_autograd logs with C++ info e.g. autograd node -> fx node mapping",
128
+ off_by_default=True,
129
+ )
130
+ register_artifact(
131
+ "ddp_graphs",
132
+ "Only relevant for compiling DDP. DDP splits into multiple graphs to trigger comms early. This will print each individual graph here.",
133
+ )
134
+ register_artifact(
135
+ "recompiles",
136
+ "Prints the reason why we recompiled a graph. Very, very useful.",
137
+ visible=True,
138
+ )
139
+ register_artifact(
140
+ "recompiles_verbose",
141
+ "Prints all guard checks that fail during a recompilation. "
142
+ "At runtime, Dynamo will stop at the first failed check for each failing guard. "
143
+ "So not all logged failing checks are actually ran by Dynamo.",
144
+ visible=True,
145
+ off_by_default=True,
146
+ )
147
+ register_artifact(
148
+ "graph_breaks",
149
+ "Prints whenever Dynamo decides that it needs to graph break (i.e. create a new graph). Useful for debugging why torch.compile has poor performance",
150
+ visible=True,
151
+ )
152
+ register_artifact(
153
+ "not_implemented",
154
+ "Prints log messages whenever we return NotImplemented in a multi-dispatch, letting you trace through each object we attempted to dispatch to",
155
+ )
156
+ register_artifact(
157
+ "output_code",
158
+ "Prints the code that Inductor generates (either Triton or C++)",
159
+ off_by_default=True,
160
+ visible=True,
161
+ )
162
+ register_artifact(
163
+ "kernel_code",
164
+ "Prints the code that Inductor generates (on a per-kernel basis)",
165
+ off_by_default=True,
166
+ visible=True,
167
+ )
168
+ register_artifact(
169
+ "schedule",
170
+ "Inductor scheduler information. Useful if working on Inductor fusion algo",
171
+ off_by_default=True,
172
+ )
173
+ register_artifact("perf_hints", "", off_by_default=True)
174
+ register_artifact("onnx_diagnostics", "", off_by_default=True)
175
+ register_artifact(
176
+ "fusion",
177
+ "Detailed Inductor fusion decisions. More detailed than 'schedule'",
178
+ off_by_default=True,
179
+ )
180
+ register_artifact(
181
+ "loop_ordering",
182
+ "Logs related to loop ordering",
183
+ off_by_default=True,
184
+ )
185
+ register_artifact(
186
+ "overlap",
187
+ "Detailed Inductor compute/comm overlap decisions",
188
+ off_by_default=True,
189
+ )
190
+ register_artifact(
191
+ "sym_node",
192
+ "Logs extra info for various SymNode operations",
193
+ off_by_default=True,
194
+ )
195
+ register_artifact(
196
+ "trace_shape_events",
197
+ "Logs traces for every ShapeEnv operation that we record for replay",
198
+ off_by_default=True,
199
+ )
200
+ register_artifact(
201
+ "cudagraph_static_inputs",
202
+ "Logs static inputs handling in dynamo, AOT, and cudagraphs",
203
+ off_by_default=True,
204
+ )
205
+ register_artifact(
206
+ "benchmarking",
207
+ "Detailed Inductor benchmarking information.",
208
+ off_by_default=True,
209
+ )
210
+ register_artifact(
211
+ "autotuning",
212
+ "Autotuning choice logs, such as kernel source, perf, and tuning parameters.",
213
+ off_by_default=True,
214
+ )
215
+ register_artifact(
216
+ "graph_region_expansion",
217
+ "Logs detailed steps of the duplicate graph region tracker expansion algorithm",
218
+ off_by_default=True,
219
+ )
220
+
221
+ register_artifact("custom_format_test_artifact", "Testing only", log_format="")
shared/package-files/41/41156e3b32edabf6cfd74c2cfd9e112b093803a883defa1b63650a1655396743/style.cpython-311.pyc ADDED
Binary file (32.2 kB). View file
 
shared/package-files/41/4118982954345ffd2515cea40c4cfba04ef6e84c8ea43044c4291f6048877a2e/test_contains.cpython-311.pyc ADDED
Binary file (3.97 kB). View file
 
shared/package-files/41/411edb7f93c2bb27df248043647e5de9d664b2afbda3e1160d725cad5c6b435e/_foreach_zero_compositeexplicitautograd_dispatch.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API ::std::vector<at::Tensor> _foreach_zero(at::TensorList self);
21
+ TORCH_API void _foreach_zero_out(at::TensorList out, at::TensorList self);
22
+ TORCH_API void _foreach_zero_outf(at::TensorList self, at::TensorList out);
23
+ TORCH_API void _foreach_zero_(at::TensorList self);
24
+
25
+ } // namespace compositeexplicitautograd
26
+ } // namespace at
shared/package-files/41/4124cc45bf65ec8f669ef4f5ffc29736a2cee3cc166961201bdedb0e3121d627/cuda_fp8.h ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2022-2024 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * NOTICE TO LICENSEE:
5
+ *
6
+ * This source code and/or documentation ("Licensed Deliverables") are
7
+ * subject to NVIDIA intellectual property rights under U.S. and
8
+ * international Copyright laws.
9
+ *
10
+ * These Licensed Deliverables contained herein is PROPRIETARY and
11
+ * CONFIDENTIAL to NVIDIA and is being provided under the terms and
12
+ * conditions of a form of NVIDIA software license agreement by and
13
+ * between NVIDIA and Licensee ("License Agreement") or electronically
14
+ * accepted by Licensee. Notwithstanding any terms or conditions to
15
+ * the contrary in the License Agreement, reproduction or disclosure
16
+ * of the Licensed Deliverables to any third party without the express
17
+ * written consent of NVIDIA is prohibited.
18
+ *
19
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
20
+ * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
21
+ * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS
22
+ * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
23
+ * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
24
+ * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
25
+ * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
26
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
27
+ * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
28
+ * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
29
+ * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
30
+ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
31
+ * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
32
+ * OF THESE LICENSED DELIVERABLES.
33
+ *
34
+ * U.S. Government End Users. These Licensed Deliverables are a
35
+ * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
36
+ * 1995), consisting of "commercial computer software" and "commercial
37
+ * computer software documentation" as such terms are used in 48
38
+ * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
39
+ * only as a commercial end item. Consistent with 48 C.F.R.12.212 and
40
+ * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
41
+ * U.S. Government End Users acquire the Licensed Deliverables with
42
+ * only those rights set forth herein.
43
+ *
44
+ * Any use of the Licensed Deliverables in individual and commercial
45
+ * software must include, in the user documentation and internal
46
+ * comments to the code, the above Disclaimer and U.S. Government End
47
+ * Users Notice.
48
+ */
49
+
50
+ #ifndef __CUDA_FP8_H__
51
+ #define __CUDA_FP8_H__
52
+
53
+ /* Set up function decorations */
54
+ #if defined(__CUDACC__)
55
+ #define __CUDA_FP8_DECL__ static __device__ __inline__
56
+ #define __CUDA_HOSTDEVICE_FP8__ __host__ __device__
57
+ #define __CUDA_HOSTDEVICE_FP8_DECL__ static __host__ __device__ __inline__
58
+ #else /* !defined(__CUDACC__) */
59
+ #if defined(__GNUC__)
60
+ #define __CUDA_HOSTDEVICE_FP8_DECL__ static __attribute__((unused))
61
+ #else
62
+ #define __CUDA_HOSTDEVICE_FP8_DECL__ static
63
+ #endif /* defined(__GNUC__) */
64
+ #define __CUDA_HOSTDEVICE_FP8__
65
+ #endif /* defined(__CUDACC_) */
66
+
67
+ #if !defined(_MSC_VER) && __cplusplus >= 201103L
68
+ #define __CPP_VERSION_AT_LEAST_11_FP8
69
+ #elif _MSC_FULL_VER >= 190024210 && _MSVC_LANG >= 201103L
70
+ #define __CPP_VERSION_AT_LEAST_11_FP8
71
+ #endif
72
+
73
+ // implicitly provided by NVRTC
74
+ #if !defined(__CUDACC_RTC__)
75
+ /* bring in enum cudaRoundMode */
76
+ #include "device_types.h"
77
+ #endif /* !defined(__CUDACC_RTC__) */
78
+
79
+ /* bring in __half_raw data type */
80
+ #include "cuda_fp16.h"
81
+ /* bring in __nv_bfloat16_raw data type */
82
+ #include "cuda_bf16.h"
83
+
84
+ // implicitly provided by NVRTC
85
+ #if !defined(__CUDACC_RTC__)
86
+ /* bring in float2, double4, etc vector types */
87
+ #include "vector_types.h"
88
+ #endif /* !defined(__CUDACC_RTC__) */
89
+
90
+ /**
91
+ * \defgroup CUDA_MATH_INTRINSIC_FP8 FP8 Intrinsics
92
+ * This section describes fp8 intrinsic functions.
93
+ * To use these functions, include the header file \p cuda_fp8.h in your
94
+ * program.
95
+ * The following macros are available to help users selectively enable/disable
96
+ * various definitions present in the header file:
97
+ * - \p __CUDA_NO_FP8_CONVERSIONS__ - If defined, this macro will prevent any
98
+ * use of the C++ type conversions (converting constructors and conversion
99
+ * operators) defined in the header.
100
+ * - \p __CUDA_NO_FP8_CONVERSION_OPERATORS__ - If defined, this macro will
101
+ * prevent any use of the C++ conversion operators from \p fp8 to other types.
102
+ */
103
+
104
+ /**
105
+ * \defgroup CUDA_MATH_FP8_MISC FP8 Conversion and Data Movement
106
+ * \ingroup CUDA_MATH_INTRINSIC_FP8
107
+ * To use these functions, include the header file \p cuda_fp8.h in your
108
+ * program.
109
+ */
110
+
111
+ /**
112
+ * \ingroup CUDA_MATH_FP8_MISC
113
+ * \brief 8-bit \p unsigned \p integer
114
+ * type abstraction used for \p fp8 floating-point
115
+ * numbers storage.
116
+ */
117
+ typedef unsigned char __nv_fp8_storage_t;
118
+
119
+ /**
120
+ * \ingroup CUDA_MATH_FP8_MISC
121
+ * \brief 16-bit \p unsigned \p integer
122
+ * type abstraction used for storage of pairs of
123
+ * \p fp8 floating-point numbers.
124
+ */
125
+ typedef unsigned short int __nv_fp8x2_storage_t;
126
+
127
+ /**
128
+ * \ingroup CUDA_MATH_FP8_MISC
129
+ * \brief 32-bit \p unsigned \p integer
130
+ * type abstraction used for storage of tetrads of
131
+ * \p fp8 floating-point numbers.
132
+ */
133
+ typedef unsigned int __nv_fp8x4_storage_t;
134
+
135
+ /**
136
+ * \ingroup CUDA_MATH_FP8_MISC
137
+ * \brief Enumerates the modes applicable when
138
+ * performing a narrowing conversion to \p fp8 destination types.
139
+ */
140
+ typedef enum __nv_saturation_t {
141
+ /**
142
+ * Means no saturation to finite is performed when conversion
143
+ * results in rounding values outside the range of destination
144
+ * type.
145
+ * NOTE: for fp8 type of e4m3 kind, the results that are larger
146
+ * than the maximum representable finite number of the target
147
+ * format become NaN.
148
+ */
149
+ __NV_NOSAT,
150
+ /**
151
+ * Means input larger than the maximum representable
152
+ * finite number MAXNORM of the target format round to the
153
+ * MAXNORM of the same sign as input.
154
+ */
155
+ __NV_SATFINITE,
156
+ } __nv_saturation_t;
157
+
158
+ /**
159
+ * \ingroup CUDA_MATH_FP8_MISC
160
+ * \brief Enumerates the possible
161
+ * interpretations of the 8-bit values when referring to them as
162
+ * \p fp8 types.
163
+ */
164
+ typedef enum __nv_fp8_interpretation_t {
165
+ __NV_E4M3, /**< Stands for \p fp8 numbers of \p e4m3 kind. */
166
+ __NV_E5M2, /**< Stands for \p fp8 numbers of \p e5m2 kind. */
167
+ } __nv_fp8_interpretation_t;
168
+
169
+ /* Forward-declaration of C-style APIs */
170
+
171
+ /**
172
+ * \ingroup CUDA_MATH_FP8_MISC
173
+ * \brief Converts input \p double precision \p x to \p fp8 type of the
174
+ * requested kind using round-to-nearest-even rounding and requested saturation
175
+ * mode.
176
+ *
177
+ * \details Converts input \p x to \p fp8 type of the kind specified by
178
+ * \p fp8_interpretation parameter,
179
+ * using round-to-nearest-even rounding and
180
+ * saturation mode specified by \p saturate parameter.
181
+ *
182
+ * \returns
183
+ * - The \p __nv_fp8_storage_t value holds the result of conversion.
184
+ */
185
+ __CUDA_HOSTDEVICE_FP8_DECL__ __nv_fp8_storage_t
186
+ __nv_cvt_double_to_fp8(const double x, const __nv_saturation_t saturate,
187
+ const __nv_fp8_interpretation_t fp8_interpretation);
188
+
189
+ /**
190
+ * \ingroup CUDA_MATH_FP8_MISC
191
+ * \brief Converts input vector of two \p double precision numbers packed
192
+ * in \p double2 \p x into a vector of two values of \p fp8 type of
193
+ * the requested kind using round-to-nearest-even rounding and requested
194
+ * saturation mode.
195
+ *
196
+ * \details Converts input vector \p x to a vector of two \p fp8 values of the
197
+ * kind specified by \p fp8_interpretation parameter, using
198
+ * round-to-nearest-even rounding and saturation mode specified by \p saturate
199
+ * parameter.
200
+ *
201
+ * \returns
202
+ * - The \p __nv_fp8x2_storage_t value holds the result of conversion.
203
+ */
204
+ __CUDA_HOSTDEVICE_FP8_DECL__ __nv_fp8x2_storage_t
205
+ __nv_cvt_double2_to_fp8x2(const double2 x, const __nv_saturation_t saturate,
206
+ const __nv_fp8_interpretation_t fp8_interpretation);
207
+
208
+ /**
209
+ * \ingroup CUDA_MATH_FP8_MISC
210
+ * \brief Converts input \p single precision \p x to \p fp8 type of the
211
+ * requested kind using round-to-nearest-even rounding and requested saturation
212
+ * mode.
213
+ *
214
+ * \details Converts input \p x to \p fp8 type of the kind specified by
215
+ * \p fp8_interpretation parameter,
216
+ * using round-to-nearest-even rounding and
217
+ * saturation mode specified by \p saturate parameter.
218
+ *
219
+ * \returns
220
+ * - The \p __nv_fp8_storage_t value holds the result of conversion.
221
+ */
222
+ __CUDA_HOSTDEVICE_FP8_DECL__ __nv_fp8_storage_t
223
+ __nv_cvt_float_to_fp8(const float x, const __nv_saturation_t saturate,
224
+ const __nv_fp8_interpretation_t fp8_interpretation);
225
+
226
+ /**
227
+ * \ingroup CUDA_MATH_FP8_MISC
228
+ * \brief Converts input vector of two \p single precision numbers packed
229
+ * in \p float2 \p x into a vector of two values of \p fp8 type of
230
+ * the requested kind using round-to-nearest-even rounding and requested
231
+ * saturation mode.
232
+ *
233
+ * \details Converts input vector \p x to a vector of two \p fp8 values of the
234
+ * kind specified by \p fp8_interpretation parameter, using
235
+ * round-to-nearest-even rounding and saturation mode specified by \p saturate
236
+ * parameter.
237
+ *
238
+ * \returns
239
+ * - The \p __nv_fp8x2_storage_t value holds the result of conversion.
240
+ */
241
+ __CUDA_HOSTDEVICE_FP8_DECL__ __nv_fp8x2_storage_t
242
+ __nv_cvt_float2_to_fp8x2(const float2 x, const __nv_saturation_t saturate,
243
+ const __nv_fp8_interpretation_t fp8_interpretation);
244
+
245
+ /**
246
+ * \ingroup CUDA_MATH_FP8_MISC
247
+ * \brief Converts input \p half precision \p x to \p fp8 type of the requested
248
+ * kind using round-to-nearest-even rounding and requested saturation mode.
249
+ *
250
+ * \details Converts input \p x to \p fp8 type of the kind specified by
251
+ * \p fp8_interpretation parameter,
252
+ * using round-to-nearest-even rounding and
253
+ * saturation mode specified by \p saturate parameter.
254
+ *
255
+ * \returns
256
+ * - The \p __nv_fp8_storage_t value holds the result of conversion.
257
+ */
258
+ __CUDA_HOSTDEVICE_FP8_DECL__ __nv_fp8_storage_t
259
+ __nv_cvt_halfraw_to_fp8(const __half_raw x, const __nv_saturation_t saturate,
260
+ const __nv_fp8_interpretation_t fp8_interpretation);
261
+
262
+ /**
263
+ * \ingroup CUDA_MATH_FP8_MISC
264
+ * \brief Converts input vector of two \p half precision numbers packed
265
+ * in \p __half2_raw \p x into a vector of two values of \p fp8 type of
266
+ * the requested kind using round-to-nearest-even rounding and requested
267
+ * saturation mode.
268
+ *
269
+ * \details Converts input vector \p x to a vector of two \p fp8 values of the
270
+ * kind specified by \p fp8_interpretation parameter, using
271
+ * round-to-nearest-even rounding and saturation mode specified by \p saturate
272
+ * parameter.
273
+ *
274
+ * \returns
275
+ * - The \p __nv_fp8x2_storage_t value holds the result of conversion.
276
+ */
277
+ __CUDA_HOSTDEVICE_FP8_DECL__ __nv_fp8x2_storage_t __nv_cvt_halfraw2_to_fp8x2(
278
+ const __half2_raw x, const __nv_saturation_t saturate,
279
+ const __nv_fp8_interpretation_t fp8_interpretation);
280
+
281
+ /**
282
+ * \ingroup CUDA_MATH_FP8_MISC
283
+ * \brief Converts input \p nv_bfloat16 precision \p x to \p fp8 type of the
284
+ * requested kind using round-to-nearest-even rounding and requested saturation
285
+ * mode.
286
+ *
287
+ * \details Converts input \p x to \p fp8 type of the kind specified by
288
+ * \p fp8_interpretation parameter,
289
+ * using round-to-nearest-even rounding and
290
+ * saturation mode specified by \p saturate parameter.
291
+ *
292
+ * \returns
293
+ * - The \p __nv_fp8_storage_t value holds the result of conversion.
294
+ */
295
+ __CUDA_HOSTDEVICE_FP8_DECL__ __nv_fp8_storage_t __nv_cvt_bfloat16raw_to_fp8(
296
+ const __nv_bfloat16_raw x, const __nv_saturation_t saturate,
297
+ const __nv_fp8_interpretation_t fp8_interpretation);
298
+
299
+ /**
300
+ * \ingroup CUDA_MATH_FP8_MISC
301
+ * \brief Converts input vector of two \p nv_bfloat16 precision numbers packed
302
+ * in \p __nv_bfloat162_raw \p x into a vector of two values of \p fp8 type of
303
+ * the requested kind using round-to-nearest-even rounding and requested
304
+ * saturation mode.
305
+ *
306
+ * \details Converts input vector \p x to a vector of two \p fp8 values of the
307
+ * kind specified by \p fp8_interpretation parameter, using
308
+ * round-to-nearest-even rounding and saturation mode specified by \p saturate
309
+ * parameter.
310
+ *
311
+ * \returns
312
+ * - The \p __nv_fp8x2_storage_t value holds the result of conversion.
313
+ */
314
+ __CUDA_HOSTDEVICE_FP8_DECL__ __nv_fp8x2_storage_t
315
+ __nv_cvt_bfloat16raw2_to_fp8x2(
316
+ const __nv_bfloat162_raw x, const __nv_saturation_t saturate,
317
+ const __nv_fp8_interpretation_t fp8_interpretation);
318
+
319
+ /**
320
+ * \ingroup CUDA_MATH_FP8_MISC
321
+ * \brief Converts input \p fp8 \p x of the specified kind
322
+ * to \p half precision.
323
+ *
324
+ * \details Converts input \p x of \p fp8 type of the kind specified by
325
+ * \p fp8_interpretation parameter
326
+ * to \p half precision.
327
+ *
328
+ * \returns
329
+ * - The \p __half_raw value holds the result of conversion.
330
+ */
331
+ __CUDA_HOSTDEVICE_FP8_DECL__ __half_raw
332
+ __nv_cvt_fp8_to_halfraw(const __nv_fp8_storage_t x,
333
+ const __nv_fp8_interpretation_t fp8_interpretation);
334
+ /**
335
+ * \ingroup CUDA_MATH_FP8_MISC
336
+ * \brief Converts input vector of two \p fp8 values of the specified kind
337
+ * to a vector of two \p half precision values packed in \p __half2_raw
338
+ * structure.
339
+ *
340
+ * \details Converts input vector \p x of \p fp8 type of the kind specified by
341
+ * \p fp8_interpretation parameter
342
+ * to a vector of two \p half precision values and returns as \p __half2_raw
343
+ * structure.
344
+ *
345
+ * \returns
346
+ * - The \p __half2_raw value holds the result of conversion.
347
+ */
348
+ __CUDA_HOSTDEVICE_FP8_DECL__ __half2_raw
349
+ __nv_cvt_fp8x2_to_halfraw2(const __nv_fp8x2_storage_t x,
350
+ const __nv_fp8_interpretation_t fp8_interpretation);
351
+
352
+
353
+ /**
354
+ * \ingroup CUDA_MATH_FP8_MISC
355
+ * \brief Converts input \p bfloat16 input into a scaling factor of \p e8m0 kind.
356
+ *
357
+ * \details Input number's absolute value is rounded to the closest power of two in the
358
+ * direction specified via \p rounding parameter. Rounded results that are
359
+ * smaller than the smallest representable target format number 2^-127 are then
360
+ * clipped to 2^-127. Results that are larger than the largest representable
361
+ * target format number 2^127 are either clipped to 2^127 if \p saturate equals
362
+ * to \p __NV_SATFINITE, or convert to \p NaN otherwise. \p NaN inputs convert
363
+ * into \p NaN output, encoded as \p 0xFF in the target format.
364
+ *
365
+ * \returns
366
+ * - The \p __nv_fp8_storage_t value holds the result of conversion.
367
+ */
368
+ __CUDA_HOSTDEVICE_FP8_DECL__ __nv_fp8_storage_t __nv_cvt_bfloat16raw_to_e8m0(const __nv_bfloat16_raw x, const __nv_saturation_t saturate, const enum cudaRoundMode rounding);
369
+
370
+ /**
371
+ * \ingroup CUDA_MATH_FP8_MISC
372
+ * \brief Converts a pair of \p bfloat16 values into a pair of scaling factors of \p e8m0 kind.
373
+ *
374
+ * \see __nv_cvt_bfloat16raw_to_e8m0() for details of conversion.
375
+ *
376
+ * \returns
377
+ * - The \p __nv_fp8x2_storage_t value holds the result of conversion.
378
+ */
379
+ __CUDA_HOSTDEVICE_FP8_DECL__ __nv_fp8x2_storage_t __nv_cvt_bfloat162raw_to_e8m0x2(const __nv_bfloat162_raw x, const __nv_saturation_t saturate, const enum cudaRoundMode rounding);
380
+
381
+ /**
382
+ * \ingroup CUDA_MATH_FP8_MISC
383
+ * \brief Converts input \p float value into a scaling factor of \p e8m0 kind.
384
+ *
385
+ * \see __nv_cvt_bfloat16raw_to_e8m0() for details of conversion.
386
+ *
387
+ * \returns
388
+ * - The \p __nv_fp8_storage_t value holds the result of conversion.
389
+ */
390
+ __CUDA_HOSTDEVICE_FP8_DECL__ __nv_fp8_storage_t __nv_cvt_float_to_e8m0(const float x, const __nv_saturation_t saturate, const enum cudaRoundMode rounding);
391
+
392
+ /**
393
+ * \ingroup CUDA_MATH_FP8_MISC
394
+ * \brief Converts a pair of \p float values into a pair of scaling factors of \p e8m0 kind.
395
+ *
396
+ * \see __nv_cvt_bfloat16raw_to_e8m0() for details of conversion.
397
+ *
398
+ * \returns
399
+ * - The \p __nv_fp8x2_storage_t value holds the result of conversion.
400
+ */
401
+ __CUDA_HOSTDEVICE_FP8_DECL__ __nv_fp8x2_storage_t __nv_cvt_float2_to_e8m0x2(const float2 x, const __nv_saturation_t saturate, const enum cudaRoundMode rounding);
402
+
403
+ /**
404
+ * \ingroup CUDA_MATH_FP8_MISC
405
+ * \brief Converts input \p double value into a scaling factor of \p e8m0 kind.
406
+ *
407
+ * \see __nv_cvt_bfloat16raw_to_e8m0() for details of conversion.
408
+ *
409
+ * \returns
410
+ * - The \p __nv_fp8_storage_t value holds the result of conversion.
411
+ */
412
+ __CUDA_HOSTDEVICE_FP8_DECL__ __nv_fp8_storage_t __nv_cvt_double_to_e8m0(const double x, const __nv_saturation_t saturate, const enum cudaRoundMode rounding);
413
+
414
+ /**
415
+ * \ingroup CUDA_MATH_FP8_MISC
416
+ * \brief Converts a pair of \p double values into a pair of scaling factors of \p e8m0 kind.
417
+ *
418
+ * \see __nv_cvt_bfloat16raw_to_e8m0() for details of conversion.
419
+ *
420
+ * \returns
421
+ * - The \p __nv_fp8x2_storage_t value holds the result of conversion.
422
+ */
423
+ __CUDA_HOSTDEVICE_FP8_DECL__ __nv_fp8x2_storage_t __nv_cvt_double2_to_e8m0x2(const double2 x, const __nv_saturation_t saturate, const enum cudaRoundMode rounding);
424
+
425
+ /**
426
+ * \ingroup CUDA_MATH_FP8_MISC
427
+ * \brief Converts input scaling factor value of \p e8m0 kind into \p bfloat16.
428
+ *
429
+ * \details Input scales are exact powers of two or a \p NaN value,
430
+ * also representable in the target format.
431
+ *
432
+ * \returns
433
+ * - The \p __nv_bfloat16_raw value holds the result of conversion.
434
+ */
435
+ __CUDA_HOSTDEVICE_FP8_DECL__ __nv_bfloat16_raw __nv_cvt_e8m0_to_bf16raw(const __nv_fp8_storage_t x);
436
+
437
+ /**
438
+ * \ingroup CUDA_MATH_FP8_MISC
439
+ * \brief Converts input pair of scaling factors of \p e8m0 kind into a pair of \p bfloat16 values.
440
+ *
441
+ * \returns
442
+ * - The \p __nv_bfloat162_raw value holds the result of conversion.
443
+ */
444
+ __CUDA_HOSTDEVICE_FP8_DECL__ __nv_bfloat162_raw __nv_cvt_e8m0x2_to_bf162raw(const __nv_fp8x2_storage_t x);
445
+
446
+ #if defined(__cplusplus)
447
+
448
+ #define __CUDA_FP8_TYPES_EXIST__
449
+
450
+ /* Forward-declaration of structures defined in "cuda_fp8.hpp" */
451
+ struct __nv_fp8_e5m2;
452
+ struct __nv_fp8x2_e5m2;
453
+ struct __nv_fp8x4_e5m2;
454
+
455
+ struct __nv_fp8_e4m3;
456
+ struct __nv_fp8x2_e4m3;
457
+ struct __nv_fp8x4_e4m3;
458
+
459
+ struct __nv_fp8_e8m0;
460
+ struct __nv_fp8x2_e8m0;
461
+ struct __nv_fp8x4_e8m0;
462
+
463
+ #endif /* defined(__cplusplus) */
464
+
465
+ #include "cuda_fp8.hpp"
466
+
467
+ #undef __CUDA_FP8_DECL__
468
+ #undef __CUDA_HOSTDEVICE_FP8__
469
+ #undef __CUDA_HOSTDEVICE_FP8_DECL__
470
+
471
+ #if defined(__CPP_VERSION_AT_LEAST_11_FP8)
472
+ #undef __CPP_VERSION_AT_LEAST_11_FP8
473
+ #endif /* defined(__CPP_VERSION_AT_LEAST_11_FP8) */
474
+
475
+ #endif /* end of include guard: __CUDA_FP8_H__ */
shared/package-files/41/412883b21ac7fc219aa23959367199aebd77be61667c879684842bc4c5c6bbe8/dimensions.cpython-311.pyc ADDED
Binary file (33.9 kB). View file
 
shared/package-files/41/412daf67230897b080ad244359767c385637fe343e05031676c8674a7624ce88/traversal.cpython-311.pyc ADDED
Binary file (2.72 kB). View file
 
shared/package-files/41/41392d016170860c41dbfd83f6a34a8338b16e42c7903b474e9daa8c0b682ca1/test_core.cpython-311.pyc ADDED
Binary file (7.83 kB). View file
 
shared/package-files/41/413a78674c3ded3d643aeecb9ea36e5edd233c0be3e6fcb057e70039105e04df/test_complexes.cpython-311.pyc ADDED
Binary file (89.9 kB). View file
 
shared/package-files/41/41401633a1f8e5806477b7d7ea35d73b78feb5f55a1e1cf16d79fb3a74a6d04b/codeprinter.py ADDED
@@ -0,0 +1,1039 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from typing import Any
3
+
4
+ from functools import wraps
5
+
6
+ from sympy.core import Add, Mul, Pow, S, sympify, Float
7
+ from sympy.core.basic import Basic
8
+ from sympy.core.expr import Expr, UnevaluatedExpr
9
+ from sympy.core.function import Lambda
10
+ from sympy.core.mul import _keep_coeff
11
+ from sympy.core.sorting import default_sort_key
12
+ from sympy.core.symbol import Symbol
13
+ from sympy.functions.elementary.complexes import re
14
+ from sympy.printing.str import StrPrinter
15
+ from sympy.printing.precedence import precedence, PRECEDENCE
16
+
17
+
18
+ class requires:
19
+ """ Decorator for registering requirements on print methods. """
20
+ def __init__(self, **kwargs):
21
+ self._req = kwargs
22
+
23
+ def __call__(self, method):
24
+ def _method_wrapper(self_, *args, **kwargs):
25
+ for k, v in self._req.items():
26
+ getattr(self_, k).update(v)
27
+ return method(self_, *args, **kwargs)
28
+ return wraps(method)(_method_wrapper)
29
+
30
+
31
+ class AssignmentError(Exception):
32
+ """
33
+ Raised if an assignment variable for a loop is missing.
34
+ """
35
+ pass
36
+
37
+ class PrintMethodNotImplementedError(NotImplementedError):
38
+ """
39
+ Raised if a _print_* method is missing in the Printer.
40
+ """
41
+ pass
42
+
43
+ def _convert_python_lists(arg):
44
+ if isinstance(arg, list):
45
+ from sympy.codegen.abstract_nodes import List
46
+ return List(*(_convert_python_lists(e) for e in arg))
47
+ elif isinstance(arg, tuple):
48
+ return tuple(_convert_python_lists(e) for e in arg)
49
+ else:
50
+ return arg
51
+
52
+
53
+ class CodePrinter(StrPrinter):
54
+ """
55
+ The base class for code-printing subclasses.
56
+ """
57
+
58
+ _operators = {
59
+ 'and': '&&',
60
+ 'or': '||',
61
+ 'not': '!',
62
+ }
63
+
64
+ _default_settings: dict[str, Any] = {
65
+ 'order': None,
66
+ 'full_prec': 'auto',
67
+ 'error_on_reserved': False,
68
+ 'reserved_word_suffix': '_',
69
+ 'human': True,
70
+ 'inline': False,
71
+ 'allow_unknown_functions': False,
72
+ 'strict': None # True or False; None => True if human == True
73
+ }
74
+
75
+ # Functions which are "simple" to rewrite to other functions that
76
+ # may be supported
77
+ # function_to_rewrite : (function_to_rewrite_to, iterable_with_other_functions_required)
78
+ _rewriteable_functions = {
79
+ 'cot': ('tan', []),
80
+ 'csc': ('sin', []),
81
+ 'sec': ('cos', []),
82
+ 'acot': ('atan', []),
83
+ 'acsc': ('asin', []),
84
+ 'asec': ('acos', []),
85
+ 'coth': ('exp', []),
86
+ 'csch': ('exp', []),
87
+ 'sech': ('exp', []),
88
+ 'acoth': ('log', []),
89
+ 'acsch': ('log', []),
90
+ 'asech': ('log', []),
91
+ 'catalan': ('gamma', []),
92
+ 'fibonacci': ('sqrt', []),
93
+ 'lucas': ('sqrt', []),
94
+ 'beta': ('gamma', []),
95
+ 'sinc': ('sin', ['Piecewise']),
96
+ 'Mod': ('floor', []),
97
+ 'factorial': ('gamma', []),
98
+ 'factorial2': ('gamma', ['Piecewise']),
99
+ 'subfactorial': ('uppergamma', []),
100
+ 'RisingFactorial': ('gamma', ['Piecewise']),
101
+ 'FallingFactorial': ('gamma', ['Piecewise']),
102
+ 'binomial': ('gamma', []),
103
+ 'frac': ('floor', []),
104
+ 'Max': ('Piecewise', []),
105
+ 'Min': ('Piecewise', []),
106
+ 'Heaviside': ('Piecewise', []),
107
+ 'erf2': ('erf', []),
108
+ 'erfc': ('erf', []),
109
+ 'Li': ('li', []),
110
+ 'Ei': ('li', []),
111
+ 'dirichlet_eta': ('zeta', []),
112
+ 'riemann_xi': ('zeta', ['gamma']),
113
+ 'SingularityFunction': ('Piecewise', []),
114
+ }
115
+
116
+ def __init__(self, settings=None):
117
+ super().__init__(settings=settings)
118
+ if self._settings.get('strict', True) == None:
119
+ # for backwards compatibility, human=False need not to throw:
120
+ self._settings['strict'] = self._settings.get('human', True) == True
121
+ if not hasattr(self, 'reserved_words'):
122
+ self.reserved_words = set()
123
+
124
+ def _handle_UnevaluatedExpr(self, expr):
125
+ return expr.replace(re, lambda arg: arg if isinstance(
126
+ arg, UnevaluatedExpr) and arg.args[0].is_real else re(arg))
127
+
128
+ def doprint(self, expr, assign_to=None):
129
+ """
130
+ Print the expression as code.
131
+
132
+ Parameters
133
+ ----------
134
+ expr : Expression
135
+ The expression to be printed.
136
+
137
+ assign_to : Symbol, string, MatrixSymbol, list of strings or Symbols (optional)
138
+ If provided, the printed code will set the expression to a variable or multiple variables
139
+ with the name or names given in ``assign_to``.
140
+ """
141
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
142
+ from sympy.codegen.ast import CodeBlock, Assignment
143
+
144
+ def _handle_assign_to(expr, assign_to):
145
+ if assign_to is None:
146
+ return sympify(expr)
147
+ if isinstance(assign_to, (list, tuple)):
148
+ if len(expr) != len(assign_to):
149
+ raise ValueError('Failed to assign an expression of length {} to {} variables'.format(len(expr), len(assign_to)))
150
+ return CodeBlock(*[_handle_assign_to(lhs, rhs) for lhs, rhs in zip(expr, assign_to)])
151
+ if isinstance(assign_to, str):
152
+ if expr.is_Matrix:
153
+ assign_to = MatrixSymbol(assign_to, *expr.shape)
154
+ else:
155
+ assign_to = Symbol(assign_to)
156
+ elif not isinstance(assign_to, Basic):
157
+ raise TypeError("{} cannot assign to object of type {}".format(
158
+ type(self).__name__, type(assign_to)))
159
+ return Assignment(assign_to, expr)
160
+
161
+ expr = _convert_python_lists(expr)
162
+ expr = _handle_assign_to(expr, assign_to)
163
+
164
+ # Remove re(...) nodes due to UnevaluatedExpr.is_real always is None:
165
+ expr = self._handle_UnevaluatedExpr(expr)
166
+
167
+ # keep a set of expressions that are not strictly translatable to Code
168
+ # and number constants that must be declared and initialized
169
+ self._not_supported = set()
170
+ self._number_symbols = set()
171
+
172
+ lines = self._print(expr).splitlines()
173
+
174
+ # format the output
175
+ if self._settings["human"]:
176
+ frontlines = []
177
+ if self._not_supported:
178
+ frontlines.append(self._get_comment(
179
+ "Not supported in {}:".format(self.language)))
180
+ for expr in sorted(self._not_supported, key=str):
181
+ frontlines.append(self._get_comment(type(expr).__name__))
182
+ for name, value in sorted(self._number_symbols, key=str):
183
+ frontlines.append(self._declare_number_const(name, value))
184
+ lines = frontlines + lines
185
+ lines = self._format_code(lines)
186
+ result = "\n".join(lines)
187
+ else:
188
+ lines = self._format_code(lines)
189
+ num_syms = {(k, self._print(v)) for k, v in self._number_symbols}
190
+ result = (num_syms, self._not_supported, "\n".join(lines))
191
+ self._not_supported = set()
192
+ self._number_symbols = set()
193
+ return result
194
+
195
+ def _doprint_loops(self, expr, assign_to=None):
196
+ # Here we print an expression that contains Indexed objects, they
197
+ # correspond to arrays in the generated code. The low-level implementation
198
+ # involves looping over array elements and possibly storing results in temporary
199
+ # variables or accumulate it in the assign_to object.
200
+
201
+ if self._settings.get('contract', True):
202
+ from sympy.tensor import get_contraction_structure
203
+ # Setup loops over non-dummy indices -- all terms need these
204
+ indices = self._get_expression_indices(expr, assign_to)
205
+ # Setup loops over dummy indices -- each term needs separate treatment
206
+ dummies = get_contraction_structure(expr)
207
+ else:
208
+ indices = []
209
+ dummies = {None: (expr,)}
210
+ openloop, closeloop = self._get_loop_opening_ending(indices)
211
+
212
+ # terms with no summations first
213
+ if None in dummies:
214
+ text = StrPrinter.doprint(self, Add(*dummies[None]))
215
+ else:
216
+ # If all terms have summations we must initialize array to Zero
217
+ text = StrPrinter.doprint(self, 0)
218
+
219
+ # skip redundant assignments (where lhs == rhs)
220
+ lhs_printed = self._print(assign_to)
221
+ lines = []
222
+ if text != lhs_printed:
223
+ lines.extend(openloop)
224
+ if assign_to is not None:
225
+ text = self._get_statement("%s = %s" % (lhs_printed, text))
226
+ lines.append(text)
227
+ lines.extend(closeloop)
228
+
229
+ # then terms with summations
230
+ for d in dummies:
231
+ if isinstance(d, tuple):
232
+ indices = self._sort_optimized(d, expr)
233
+ openloop_d, closeloop_d = self._get_loop_opening_ending(
234
+ indices)
235
+
236
+ for term in dummies[d]:
237
+ if term in dummies and not ([list(f.keys()) for f in dummies[term]]
238
+ == [[None] for f in dummies[term]]):
239
+ # If one factor in the term has it's own internal
240
+ # contractions, those must be computed first.
241
+ # (temporary variables?)
242
+ raise NotImplementedError(
243
+ "FIXME: no support for contractions in factor yet")
244
+ else:
245
+
246
+ # We need the lhs expression as an accumulator for
247
+ # the loops, i.e
248
+ #
249
+ # for (int d=0; d < dim; d++){
250
+ # lhs[] = lhs[] + term[][d]
251
+ # } ^.................. the accumulator
252
+ #
253
+ # We check if the expression already contains the
254
+ # lhs, and raise an exception if it does, as that
255
+ # syntax is currently undefined. FIXME: What would be
256
+ # a good interpretation?
257
+ if assign_to is None:
258
+ raise AssignmentError(
259
+ "need assignment variable for loops")
260
+ if term.has(assign_to):
261
+ raise ValueError("FIXME: lhs present in rhs,\
262
+ this is undefined in CodePrinter")
263
+
264
+ lines.extend(openloop)
265
+ lines.extend(openloop_d)
266
+ text = "%s = %s" % (lhs_printed, StrPrinter.doprint(
267
+ self, assign_to + term))
268
+ lines.append(self._get_statement(text))
269
+ lines.extend(closeloop_d)
270
+ lines.extend(closeloop)
271
+
272
+ return "\n".join(lines)
273
+
274
+ def _get_expression_indices(self, expr, assign_to):
275
+ from sympy.tensor import get_indices
276
+ rinds, junk = get_indices(expr)
277
+ linds, junk = get_indices(assign_to)
278
+
279
+ # support broadcast of scalar
280
+ if linds and not rinds:
281
+ rinds = linds
282
+ if rinds != linds:
283
+ raise ValueError("lhs indices must match non-dummy"
284
+ " rhs indices in %s" % expr)
285
+
286
+ return self._sort_optimized(rinds, assign_to)
287
+
288
+ def _sort_optimized(self, indices, expr):
289
+
290
+ from sympy.tensor.indexed import Indexed
291
+
292
+ if not indices:
293
+ return []
294
+
295
+ # determine optimized loop order by giving a score to each index
296
+ # the index with the highest score are put in the innermost loop.
297
+ score_table = {}
298
+ for i in indices:
299
+ score_table[i] = 0
300
+
301
+ arrays = expr.atoms(Indexed)
302
+ for arr in arrays:
303
+ for p, ind in enumerate(arr.indices):
304
+ try:
305
+ score_table[ind] += self._rate_index_position(p)
306
+ except KeyError:
307
+ pass
308
+
309
+ return sorted(indices, key=lambda x: score_table[x])
310
+
311
+ def _rate_index_position(self, p):
312
+ """function to calculate score based on position among indices
313
+
314
+ This method is used to sort loops in an optimized order, see
315
+ CodePrinter._sort_optimized()
316
+ """
317
+ raise NotImplementedError("This function must be implemented by "
318
+ "subclass of CodePrinter.")
319
+
320
+ def _get_statement(self, codestring):
321
+ """Formats a codestring with the proper line ending."""
322
+ raise NotImplementedError("This function must be implemented by "
323
+ "subclass of CodePrinter.")
324
+
325
+ def _get_comment(self, text):
326
+ """Formats a text string as a comment."""
327
+ raise NotImplementedError("This function must be implemented by "
328
+ "subclass of CodePrinter.")
329
+
330
+ def _declare_number_const(self, name, value):
331
+ """Declare a numeric constant at the top of a function"""
332
+ raise NotImplementedError("This function must be implemented by "
333
+ "subclass of CodePrinter.")
334
+
335
+ def _format_code(self, lines):
336
+ """Take in a list of lines of code, and format them accordingly.
337
+
338
+ This may include indenting, wrapping long lines, etc..."""
339
+ raise NotImplementedError("This function must be implemented by "
340
+ "subclass of CodePrinter.")
341
+
342
+ def _get_loop_opening_ending(self, indices):
343
+ """Returns a tuple (open_lines, close_lines) containing lists
344
+ of codelines"""
345
+ raise NotImplementedError("This function must be implemented by "
346
+ "subclass of CodePrinter.")
347
+
348
+ def _print_Dummy(self, expr):
349
+ if expr.name.startswith('Dummy_'):
350
+ return '_' + expr.name
351
+ else:
352
+ return '%s_%d' % (expr.name, expr.dummy_index)
353
+
354
+ def _print_Idx(self, expr):
355
+ return self._print(expr.label)
356
+
357
+ def _print_CodeBlock(self, expr):
358
+ return '\n'.join([self._print(i) for i in expr.args])
359
+
360
+ def _print_String(self, string):
361
+ return str(string)
362
+
363
+ def _print_QuotedString(self, arg):
364
+ return '"%s"' % arg.text
365
+
366
+ def _print_Comment(self, string):
367
+ return self._get_comment(str(string))
368
+
369
+ def _print_Assignment(self, expr):
370
+ from sympy.codegen.ast import Assignment
371
+ from sympy.functions.elementary.piecewise import Piecewise
372
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
373
+ from sympy.tensor.indexed import IndexedBase
374
+ lhs = expr.lhs
375
+ rhs = expr.rhs
376
+ # We special case assignments that take multiple lines
377
+ if isinstance(expr.rhs, Piecewise):
378
+ # Here we modify Piecewise so each expression is now
379
+ # an Assignment, and then continue on the print.
380
+ expressions = []
381
+ conditions = []
382
+ for (e, c) in rhs.args:
383
+ expressions.append(Assignment(lhs, e))
384
+ conditions.append(c)
385
+ temp = Piecewise(*zip(expressions, conditions))
386
+ return self._print(temp)
387
+ elif isinstance(lhs, MatrixSymbol):
388
+ # Here we form an Assignment for each element in the array,
389
+ # printing each one.
390
+ lines = []
391
+ for (i, j) in self._traverse_matrix_indices(lhs):
392
+ temp = Assignment(lhs[i, j], rhs[i, j])
393
+ code0 = self._print(temp)
394
+ lines.append(code0)
395
+ return "\n".join(lines)
396
+ elif self._settings.get("contract", False) and (lhs.has(IndexedBase) or
397
+ rhs.has(IndexedBase)):
398
+ # Here we check if there is looping to be done, and if so
399
+ # print the required loops.
400
+ return self._doprint_loops(rhs, lhs)
401
+ else:
402
+ lhs_code = self._print(lhs)
403
+ rhs_code = self._print(rhs)
404
+ return self._get_statement("%s = %s" % (lhs_code, rhs_code))
405
+
406
+ def _print_AugmentedAssignment(self, expr):
407
+ lhs_code = self._print(expr.lhs)
408
+ rhs_code = self._print(expr.rhs)
409
+ return self._get_statement("{} {} {}".format(
410
+ *(self._print(arg) for arg in [lhs_code, expr.op, rhs_code])))
411
+
412
+ def _print_FunctionCall(self, expr):
413
+ return '%s(%s)' % (
414
+ expr.name,
415
+ ', '.join((self._print(arg) for arg in expr.function_args)))
416
+
417
+ def _print_Variable(self, expr):
418
+ return self._print(expr.symbol)
419
+
420
+ def _print_Symbol(self, expr):
421
+ name = super()._print_Symbol(expr)
422
+
423
+ if name in self.reserved_words:
424
+ if self._settings['error_on_reserved']:
425
+ msg = ('This expression includes the symbol "{}" which is a '
426
+ 'reserved keyword in this language.')
427
+ raise ValueError(msg.format(name))
428
+ return name + self._settings['reserved_word_suffix']
429
+ else:
430
+ return name
431
+
432
+ def _can_print(self, name):
433
+ """ Check if function ``name`` is either a known function or has its own
434
+ printing method. Used to check if rewriting is possible."""
435
+ return name in self.known_functions or getattr(self, '_print_{}'.format(name), False)
436
+
437
+ def _print_Function(self, expr):
438
+ if expr.func.__name__ in self.known_functions:
439
+ cond_func = self.known_functions[expr.func.__name__]
440
+ if isinstance(cond_func, str):
441
+ return "%s(%s)" % (cond_func, self.stringify(expr.args, ", "))
442
+ else:
443
+ for cond, func in cond_func:
444
+ if cond(*expr.args):
445
+ break
446
+ if func is not None:
447
+ try:
448
+ return func(*[self.parenthesize(item, 0) for item in expr.args])
449
+ except TypeError:
450
+ return "%s(%s)" % (func, self.stringify(expr.args, ", "))
451
+ elif hasattr(expr, '_imp_') and isinstance(expr._imp_, Lambda):
452
+ # inlined function
453
+ return self._print(expr._imp_(*expr.args))
454
+ elif expr.func.__name__ in self._rewriteable_functions:
455
+ # Simple rewrite to supported function possible
456
+ target_f, required_fs = self._rewriteable_functions[expr.func.__name__]
457
+ if self._can_print(target_f) and all(self._can_print(f) for f in required_fs):
458
+ return '(' + self._print(expr.rewrite(target_f)) + ')'
459
+
460
+ if expr.is_Function and self._settings.get('allow_unknown_functions', False):
461
+ return '%s(%s)' % (self._print(expr.func), ', '.join(map(self._print, expr.args)))
462
+ else:
463
+ return self._print_not_supported(expr)
464
+
465
+ _print_Expr = _print_Function
466
+
467
+ def _print_Derivative(self, expr):
468
+ obj, *wrt_order_pairs = expr.args
469
+ for func_arg in obj.args:
470
+ if not func_arg.is_Symbol:
471
+ raise ValueError("%s._print_Derivative(...) only supports functions with symbols as arguments." %
472
+ self.__class__.__name__)
473
+ meth_name = '_print_Derivative_%s' % obj.func.__name__
474
+ pmeth = getattr(self, meth_name, None)
475
+ if pmeth is None:
476
+ if self._settings.get('strict', False):
477
+ raise PrintMethodNotImplementedError(
478
+ f"Unsupported by {type(self)}: {type(expr)}" +
479
+ f"\nPrinter has no method: {meth_name}" +
480
+ "\nSet the printer option 'strict' to False in order to generate partially printed code."
481
+ )
482
+ return self._print_not_supported(expr)
483
+ orders = dict(wrt_order_pairs)
484
+ seq_orders = [orders[arg] for arg in obj.args]
485
+ return pmeth(obj.args, seq_orders)
486
+
487
+ # Don't inherit the str-printer method for Heaviside to the code printers
488
+ _print_Heaviside = None
489
+
490
+ def _print_NumberSymbol(self, expr):
491
+ if self._settings.get("inline", False):
492
+ return self._print(Float(expr.evalf(self._settings["precision"])))
493
+ else:
494
+ # A Number symbol that is not implemented here or with _printmethod
495
+ # is registered and evaluated
496
+ self._number_symbols.add((expr,
497
+ Float(expr.evalf(self._settings["precision"]))))
498
+ return str(expr)
499
+
500
+ def _print_Catalan(self, expr):
501
+ return self._print_NumberSymbol(expr)
502
+ def _print_EulerGamma(self, expr):
503
+ return self._print_NumberSymbol(expr)
504
+ def _print_GoldenRatio(self, expr):
505
+ return self._print_NumberSymbol(expr)
506
+ def _print_TribonacciConstant(self, expr):
507
+ return self._print_NumberSymbol(expr)
508
+ def _print_Exp1(self, expr):
509
+ return self._print_NumberSymbol(expr)
510
+ def _print_Pi(self, expr):
511
+ return self._print_NumberSymbol(expr)
512
+
513
+ def _print_And(self, expr):
514
+ PREC = precedence(expr)
515
+ return (" %s " % self._operators['and']).join(self.parenthesize(a, PREC)
516
+ for a in sorted(expr.args, key=default_sort_key))
517
+
518
+ def _print_Or(self, expr):
519
+ PREC = precedence(expr)
520
+ return (" %s " % self._operators['or']).join(self.parenthesize(a, PREC)
521
+ for a in sorted(expr.args, key=default_sort_key))
522
+
523
+ def _print_Xor(self, expr):
524
+ if self._operators.get('xor') is None:
525
+ return self._print(expr.to_nnf())
526
+ PREC = precedence(expr)
527
+ return (" %s " % self._operators['xor']).join(self.parenthesize(a, PREC)
528
+ for a in expr.args)
529
+
530
+ def _print_Equivalent(self, expr):
531
+ if self._operators.get('equivalent') is None:
532
+ return self._print(expr.to_nnf())
533
+ PREC = precedence(expr)
534
+ return (" %s " % self._operators['equivalent']).join(self.parenthesize(a, PREC)
535
+ for a in expr.args)
536
+
537
+ def _print_Not(self, expr):
538
+ PREC = precedence(expr)
539
+ return self._operators['not'] + self.parenthesize(expr.args[0], PREC)
540
+
541
+ def _print_BooleanFunction(self, expr):
542
+ return self._print(expr.to_nnf())
543
+
544
+ def _print_isnan(self, arg):
545
+ return 'isnan(%s)' % self._print(*arg.args)
546
+
547
+ def _print_isinf(self, arg):
548
+ return 'isinf(%s)' % self._print(*arg.args)
549
+
550
+ def _print_Mul(self, expr):
551
+
552
+ prec = precedence(expr)
553
+
554
+ c, e = expr.as_coeff_Mul()
555
+ if c < 0:
556
+ expr = _keep_coeff(-c, e)
557
+ sign = "-"
558
+ else:
559
+ sign = ""
560
+
561
+ a = [] # items in the numerator
562
+ b = [] # items that are in the denominator (if any)
563
+
564
+ pow_paren = [] # Will collect all pow with more than one base element and exp = -1
565
+
566
+ if self.order not in ('old', 'none'):
567
+ args = expr.as_ordered_factors()
568
+ else:
569
+ # use make_args in case expr was something like -x -> x
570
+ args = Mul.make_args(expr)
571
+
572
+ # Gather args for numerator/denominator
573
+ for item in args:
574
+ if item.is_commutative and item.is_Pow and item.exp.is_Rational and item.exp.is_negative:
575
+ if item.exp != -1:
576
+ b.append(Pow(item.base, -item.exp, evaluate=False))
577
+ else:
578
+ if len(item.args[0].args) != 1 and isinstance(item.base, Mul): # To avoid situations like #14160
579
+ pow_paren.append(item)
580
+ b.append(Pow(item.base, -item.exp))
581
+ else:
582
+ a.append(item)
583
+
584
+ a = a or [S.One]
585
+
586
+ if len(a) == 1 and sign == "-":
587
+ # Unary minus does not have a SymPy class, and hence there's no
588
+ # precedence weight associated with it, Python's unary minus has
589
+ # an operator precedence between multiplication and exponentiation,
590
+ # so we use this to compute a weight.
591
+ a_str = [self.parenthesize(a[0], 0.5*(PRECEDENCE["Pow"]+PRECEDENCE["Mul"]))]
592
+ else:
593
+ a_str = [self.parenthesize(x, prec) for x in a]
594
+ b_str = [self.parenthesize(x, prec) for x in b]
595
+
596
+ # To parenthesize Pow with exp = -1 and having more than one Symbol
597
+ for item in pow_paren:
598
+ if item.base in b:
599
+ b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)]
600
+
601
+ if not b:
602
+ return sign + '*'.join(a_str)
603
+ elif len(b) == 1:
604
+ return sign + '*'.join(a_str) + "/" + b_str[0]
605
+ else:
606
+ return sign + '*'.join(a_str) + "/(%s)" % '*'.join(b_str)
607
+
608
+ def _print_not_supported(self, expr):
609
+ if self._settings.get('strict', False):
610
+ raise PrintMethodNotImplementedError(
611
+ f"Unsupported by {type(self)}: {type(expr)}" +
612
+ "\nSet the printer option 'strict' to False in order to generate partially printed code."
613
+ )
614
+ try:
615
+ self._not_supported.add(expr)
616
+ except TypeError:
617
+ # not hashable
618
+ pass
619
+ return self.emptyPrinter(expr)
620
+
621
+ # The following can not be simply translated into C or Fortran
622
+ _print_Basic = _print_not_supported
623
+ _print_ComplexInfinity = _print_not_supported
624
+ _print_ExprCondPair = _print_not_supported
625
+ _print_GeometryEntity = _print_not_supported
626
+ _print_Infinity = _print_not_supported
627
+ _print_Integral = _print_not_supported
628
+ _print_Interval = _print_not_supported
629
+ _print_AccumulationBounds = _print_not_supported
630
+ _print_Limit = _print_not_supported
631
+ _print_MatrixBase = _print_not_supported
632
+ _print_DeferredVector = _print_not_supported
633
+ _print_NaN = _print_not_supported
634
+ _print_NegativeInfinity = _print_not_supported
635
+ _print_Order = _print_not_supported
636
+ _print_RootOf = _print_not_supported
637
+ _print_RootsOf = _print_not_supported
638
+ _print_RootSum = _print_not_supported
639
+ _print_Uniform = _print_not_supported
640
+ _print_Unit = _print_not_supported
641
+ _print_Wild = _print_not_supported
642
+ _print_WildFunction = _print_not_supported
643
+ _print_Relational = _print_not_supported
644
+
645
+
646
+ # Code printer functions. These are included in this file so that they can be
647
+ # imported in the top-level __init__.py without importing the sympy.codegen
648
+ # module.
649
+
650
+ def ccode(expr, assign_to=None, standard='c99', **settings):
651
+ """Converts an expr to a string of c code
652
+
653
+ Parameters
654
+ ==========
655
+
656
+ expr : Expr
657
+ A SymPy expression to be converted.
658
+ assign_to : optional
659
+ When given, the argument is used as the name of the variable to which
660
+ the expression is assigned. Can be a string, ``Symbol``,
661
+ ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
662
+ line-wrapping, or for expressions that generate multi-line statements.
663
+ standard : str, optional
664
+ String specifying the standard. If your compiler supports a more modern
665
+ standard you may set this to 'c99' to allow the printer to use more math
666
+ functions. [default='c89'].
667
+ precision : integer, optional
668
+ The precision for numbers such as pi [default=17].
669
+ user_functions : dict, optional
670
+ A dictionary where the keys are string representations of either
671
+ ``FunctionClass`` or ``UndefinedFunction`` instances and the values
672
+ are their desired C string representations. Alternatively, the
673
+ dictionary value can be a list of tuples i.e. [(argument_test,
674
+ cfunction_string)] or [(argument_test, cfunction_formater)]. See below
675
+ for examples.
676
+ dereference : iterable, optional
677
+ An iterable of symbols that should be dereferenced in the printed code
678
+ expression. These would be values passed by address to the function.
679
+ For example, if ``dereference=[a]``, the resulting code would print
680
+ ``(*a)`` instead of ``a``.
681
+ human : bool, optional
682
+ If True, the result is a single string that may contain some constant
683
+ declarations for the number symbols. If False, the same information is
684
+ returned in a tuple of (symbols_to_declare, not_supported_functions,
685
+ code_text). [default=True].
686
+ contract: bool, optional
687
+ If True, ``Indexed`` instances are assumed to obey tensor contraction
688
+ rules and the corresponding nested loops over indices are generated.
689
+ Setting contract=False will not generate loops, instead the user is
690
+ responsible to provide values for the indices in the code.
691
+ [default=True].
692
+
693
+ Examples
694
+ ========
695
+
696
+ >>> from sympy import ccode, symbols, Rational, sin, ceiling, Abs, Function
697
+ >>> x, tau = symbols("x, tau")
698
+ >>> expr = (2*tau)**Rational(7, 2)
699
+ >>> ccode(expr)
700
+ '8*M_SQRT2*pow(tau, 7.0/2.0)'
701
+ >>> ccode(expr, math_macros={})
702
+ '8*sqrt(2)*pow(tau, 7.0/2.0)'
703
+ >>> ccode(sin(x), assign_to="s")
704
+ 's = sin(x);'
705
+ >>> from sympy.codegen.ast import real, float80
706
+ >>> ccode(expr, type_aliases={real: float80})
707
+ '8*M_SQRT2l*powl(tau, 7.0L/2.0L)'
708
+
709
+ Simple custom printing can be defined for certain types by passing a
710
+ dictionary of {"type" : "function"} to the ``user_functions`` kwarg.
711
+ Alternatively, the dictionary value can be a list of tuples i.e.
712
+ [(argument_test, cfunction_string)].
713
+
714
+ >>> custom_functions = {
715
+ ... "ceiling": "CEIL",
716
+ ... "Abs": [(lambda x: not x.is_integer, "fabs"),
717
+ ... (lambda x: x.is_integer, "ABS")],
718
+ ... "func": "f"
719
+ ... }
720
+ >>> func = Function('func')
721
+ >>> ccode(func(Abs(x) + ceiling(x)), standard='C89', user_functions=custom_functions)
722
+ 'f(fabs(x) + CEIL(x))'
723
+
724
+ or if the C-function takes a subset of the original arguments:
725
+
726
+ >>> ccode(2**x + 3**x, standard='C99', user_functions={'Pow': [
727
+ ... (lambda b, e: b == 2, lambda b, e: 'exp2(%s)' % e),
728
+ ... (lambda b, e: b != 2, 'pow')]})
729
+ 'exp2(x) + pow(3, x)'
730
+
731
+ ``Piecewise`` expressions are converted into conditionals. If an
732
+ ``assign_to`` variable is provided an if statement is created, otherwise
733
+ the ternary operator is used. Note that if the ``Piecewise`` lacks a
734
+ default term, represented by ``(expr, True)`` then an error will be thrown.
735
+ This is to prevent generating an expression that may not evaluate to
736
+ anything.
737
+
738
+ >>> from sympy import Piecewise
739
+ >>> expr = Piecewise((x + 1, x > 0), (x, True))
740
+ >>> print(ccode(expr, tau, standard='C89'))
741
+ if (x > 0) {
742
+ tau = x + 1;
743
+ }
744
+ else {
745
+ tau = x;
746
+ }
747
+
748
+ Support for loops is provided through ``Indexed`` types. With
749
+ ``contract=True`` these expressions will be turned into loops, whereas
750
+ ``contract=False`` will just print the assignment expression that should be
751
+ looped over:
752
+
753
+ >>> from sympy import Eq, IndexedBase, Idx
754
+ >>> len_y = 5
755
+ >>> y = IndexedBase('y', shape=(len_y,))
756
+ >>> t = IndexedBase('t', shape=(len_y,))
757
+ >>> Dy = IndexedBase('Dy', shape=(len_y-1,))
758
+ >>> i = Idx('i', len_y-1)
759
+ >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
760
+ >>> ccode(e.rhs, assign_to=e.lhs, contract=False, standard='C89')
761
+ 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
762
+
763
+ Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
764
+ must be provided to ``assign_to``. Note that any expression that can be
765
+ generated normally can also exist inside a Matrix:
766
+
767
+ >>> from sympy import Matrix, MatrixSymbol
768
+ >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
769
+ >>> A = MatrixSymbol('A', 3, 1)
770
+ >>> print(ccode(mat, A, standard='C89'))
771
+ A[0] = pow(x, 2);
772
+ if (x > 0) {
773
+ A[1] = x + 1;
774
+ }
775
+ else {
776
+ A[1] = x;
777
+ }
778
+ A[2] = sin(x);
779
+ """
780
+ from sympy.printing.c import c_code_printers
781
+ return c_code_printers[standard.lower()](settings).doprint(expr, assign_to)
782
+
783
+ def print_ccode(expr, **settings):
784
+ """Prints C representation of the given expression."""
785
+ print(ccode(expr, **settings))
786
+
787
+ def fcode(expr, assign_to=None, **settings):
788
+ """Converts an expr to a string of fortran code
789
+
790
+ Parameters
791
+ ==========
792
+
793
+ expr : Expr
794
+ A SymPy expression to be converted.
795
+ assign_to : optional
796
+ When given, the argument is used as the name of the variable to which
797
+ the expression is assigned. Can be a string, ``Symbol``,
798
+ ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
799
+ line-wrapping, or for expressions that generate multi-line statements.
800
+ precision : integer, optional
801
+ DEPRECATED. Use type_mappings instead. The precision for numbers such
802
+ as pi [default=17].
803
+ user_functions : dict, optional
804
+ A dictionary where keys are ``FunctionClass`` instances and values are
805
+ their string representations. Alternatively, the dictionary value can
806
+ be a list of tuples i.e. [(argument_test, cfunction_string)]. See below
807
+ for examples.
808
+ human : bool, optional
809
+ If True, the result is a single string that may contain some constant
810
+ declarations for the number symbols. If False, the same information is
811
+ returned in a tuple of (symbols_to_declare, not_supported_functions,
812
+ code_text). [default=True].
813
+ contract: bool, optional
814
+ If True, ``Indexed`` instances are assumed to obey tensor contraction
815
+ rules and the corresponding nested loops over indices are generated.
816
+ Setting contract=False will not generate loops, instead the user is
817
+ responsible to provide values for the indices in the code.
818
+ [default=True].
819
+ source_format : optional
820
+ The source format can be either 'fixed' or 'free'. [default='fixed']
821
+ standard : integer, optional
822
+ The Fortran standard to be followed. This is specified as an integer.
823
+ Acceptable standards are 66, 77, 90, 95, 2003, and 2008. Default is 77.
824
+ Note that currently the only distinction internally is between
825
+ standards before 95, and those 95 and after. This may change later as
826
+ more features are added.
827
+ name_mangling : bool, optional
828
+ If True, then the variables that would become identical in
829
+ case-insensitive Fortran are mangled by appending different number
830
+ of ``_`` at the end. If False, SymPy Will not interfere with naming of
831
+ variables. [default=True]
832
+
833
+ Examples
834
+ ========
835
+
836
+ >>> from sympy import fcode, symbols, Rational, sin, ceiling, floor
837
+ >>> x, tau = symbols("x, tau")
838
+ >>> fcode((2*tau)**Rational(7, 2))
839
+ ' 8*sqrt(2.0d0)*tau**(7.0d0/2.0d0)'
840
+ >>> fcode(sin(x), assign_to="s")
841
+ ' s = sin(x)'
842
+
843
+ Custom printing can be defined for certain types by passing a dictionary of
844
+ "type" : "function" to the ``user_functions`` kwarg. Alternatively, the
845
+ dictionary value can be a list of tuples i.e. [(argument_test,
846
+ cfunction_string)].
847
+
848
+ >>> custom_functions = {
849
+ ... "ceiling": "CEIL",
850
+ ... "floor": [(lambda x: not x.is_integer, "FLOOR1"),
851
+ ... (lambda x: x.is_integer, "FLOOR2")]
852
+ ... }
853
+ >>> fcode(floor(x) + ceiling(x), user_functions=custom_functions)
854
+ ' CEIL(x) + FLOOR1(x)'
855
+
856
+ ``Piecewise`` expressions are converted into conditionals. If an
857
+ ``assign_to`` variable is provided an if statement is created, otherwise
858
+ the ternary operator is used. Note that if the ``Piecewise`` lacks a
859
+ default term, represented by ``(expr, True)`` then an error will be thrown.
860
+ This is to prevent generating an expression that may not evaluate to
861
+ anything.
862
+
863
+ >>> from sympy import Piecewise
864
+ >>> expr = Piecewise((x + 1, x > 0), (x, True))
865
+ >>> print(fcode(expr, tau))
866
+ if (x > 0) then
867
+ tau = x + 1
868
+ else
869
+ tau = x
870
+ end if
871
+
872
+ Support for loops is provided through ``Indexed`` types. With
873
+ ``contract=True`` these expressions will be turned into loops, whereas
874
+ ``contract=False`` will just print the assignment expression that should be
875
+ looped over:
876
+
877
+ >>> from sympy import Eq, IndexedBase, Idx
878
+ >>> len_y = 5
879
+ >>> y = IndexedBase('y', shape=(len_y,))
880
+ >>> t = IndexedBase('t', shape=(len_y,))
881
+ >>> Dy = IndexedBase('Dy', shape=(len_y-1,))
882
+ >>> i = Idx('i', len_y-1)
883
+ >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
884
+ >>> fcode(e.rhs, assign_to=e.lhs, contract=False)
885
+ ' Dy(i) = (y(i + 1) - y(i))/(t(i + 1) - t(i))'
886
+
887
+ Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
888
+ must be provided to ``assign_to``. Note that any expression that can be
889
+ generated normally can also exist inside a Matrix:
890
+
891
+ >>> from sympy import Matrix, MatrixSymbol
892
+ >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
893
+ >>> A = MatrixSymbol('A', 3, 1)
894
+ >>> print(fcode(mat, A))
895
+ A(1, 1) = x**2
896
+ if (x > 0) then
897
+ A(2, 1) = x + 1
898
+ else
899
+ A(2, 1) = x
900
+ end if
901
+ A(3, 1) = sin(x)
902
+ """
903
+ from sympy.printing.fortran import FCodePrinter
904
+ return FCodePrinter(settings).doprint(expr, assign_to)
905
+
906
+
907
+ def print_fcode(expr, **settings):
908
+ """Prints the Fortran representation of the given expression.
909
+
910
+ See fcode for the meaning of the optional arguments.
911
+ """
912
+ print(fcode(expr, **settings))
913
+
914
+ def cxxcode(expr, assign_to=None, standard='c++11', **settings):
915
+ """ C++ equivalent of :func:`~.ccode`. """
916
+ from sympy.printing.cxx import cxx_code_printers
917
+ return cxx_code_printers[standard.lower()](settings).doprint(expr, assign_to)
918
+
919
+
920
+ def rust_code(expr, assign_to=None, **settings):
921
+ """Converts an expr to a string of Rust code
922
+
923
+ Parameters
924
+ ==========
925
+
926
+ expr : Expr
927
+ A SymPy expression to be converted.
928
+ assign_to : optional
929
+ When given, the argument is used as the name of the variable to which
930
+ the expression is assigned. Can be a string, ``Symbol``,
931
+ ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
932
+ line-wrapping, or for expressions that generate multi-line statements.
933
+ precision : integer, optional
934
+ The precision for numbers such as pi [default=15].
935
+ user_functions : dict, optional
936
+ A dictionary where the keys are string representations of either
937
+ ``FunctionClass`` or ``UndefinedFunction`` instances and the values
938
+ are their desired C string representations. Alternatively, the
939
+ dictionary value can be a list of tuples i.e. [(argument_test,
940
+ cfunction_string)]. See below for examples.
941
+ dereference : iterable, optional
942
+ An iterable of symbols that should be dereferenced in the printed code
943
+ expression. These would be values passed by address to the function.
944
+ For example, if ``dereference=[a]``, the resulting code would print
945
+ ``(*a)`` instead of ``a``.
946
+ human : bool, optional
947
+ If True, the result is a single string that may contain some constant
948
+ declarations for the number symbols. If False, the same information is
949
+ returned in a tuple of (symbols_to_declare, not_supported_functions,
950
+ code_text). [default=True].
951
+ contract: bool, optional
952
+ If True, ``Indexed`` instances are assumed to obey tensor contraction
953
+ rules and the corresponding nested loops over indices are generated.
954
+ Setting contract=False will not generate loops, instead the user is
955
+ responsible to provide values for the indices in the code.
956
+ [default=True].
957
+
958
+ Examples
959
+ ========
960
+
961
+ >>> from sympy import rust_code, symbols, Rational, sin, ceiling, Abs, Function
962
+ >>> x, tau = symbols("x, tau")
963
+ >>> rust_code((2*tau)**Rational(7, 2))
964
+ '8.0*1.4142135623731*tau.powf(7_f64/2.0)'
965
+ >>> rust_code(sin(x), assign_to="s")
966
+ 's = x.sin();'
967
+
968
+ Simple custom printing can be defined for certain types by passing a
969
+ dictionary of {"type" : "function"} to the ``user_functions`` kwarg.
970
+ Alternatively, the dictionary value can be a list of tuples i.e.
971
+ [(argument_test, cfunction_string)].
972
+
973
+ >>> custom_functions = {
974
+ ... "ceiling": "CEIL",
975
+ ... "Abs": [(lambda x: not x.is_integer, "fabs", 4),
976
+ ... (lambda x: x.is_integer, "ABS", 4)],
977
+ ... "func": "f"
978
+ ... }
979
+ >>> func = Function('func')
980
+ >>> rust_code(func(Abs(x) + ceiling(x)), user_functions=custom_functions)
981
+ '(fabs(x) + x.ceil()).f()'
982
+
983
+ ``Piecewise`` expressions are converted into conditionals. If an
984
+ ``assign_to`` variable is provided an if statement is created, otherwise
985
+ the ternary operator is used. Note that if the ``Piecewise`` lacks a
986
+ default term, represented by ``(expr, True)`` then an error will be thrown.
987
+ This is to prevent generating an expression that may not evaluate to
988
+ anything.
989
+
990
+ >>> from sympy import Piecewise
991
+ >>> expr = Piecewise((x + 1, x > 0), (x, True))
992
+ >>> print(rust_code(expr, tau))
993
+ tau = if (x > 0.0) {
994
+ x + 1
995
+ } else {
996
+ x
997
+ };
998
+
999
+ Support for loops is provided through ``Indexed`` types. With
1000
+ ``contract=True`` these expressions will be turned into loops, whereas
1001
+ ``contract=False`` will just print the assignment expression that should be
1002
+ looped over:
1003
+
1004
+ >>> from sympy import Eq, IndexedBase, Idx
1005
+ >>> len_y = 5
1006
+ >>> y = IndexedBase('y', shape=(len_y,))
1007
+ >>> t = IndexedBase('t', shape=(len_y,))
1008
+ >>> Dy = IndexedBase('Dy', shape=(len_y-1,))
1009
+ >>> i = Idx('i', len_y-1)
1010
+ >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
1011
+ >>> rust_code(e.rhs, assign_to=e.lhs, contract=False)
1012
+ 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
1013
+
1014
+ Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
1015
+ must be provided to ``assign_to``. Note that any expression that can be
1016
+ generated normally can also exist inside a Matrix:
1017
+
1018
+ >>> from sympy import Matrix, MatrixSymbol
1019
+ >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
1020
+ >>> A = MatrixSymbol('A', 3, 1)
1021
+ >>> print(rust_code(mat, A))
1022
+ A = [x.powi(2), if (x > 0.0) {
1023
+ x + 1
1024
+ } else {
1025
+ x
1026
+ }, x.sin()];
1027
+ """
1028
+ from sympy.printing.rust import RustCodePrinter
1029
+ printer = RustCodePrinter(settings)
1030
+ expr = printer._rewrite_known_functions(expr)
1031
+ if isinstance(expr, Expr):
1032
+ for src_func, dst_func in printer.function_overrides.values():
1033
+ expr = expr.replace(src_func, dst_func)
1034
+ return printer.doprint(expr, assign_to)
1035
+
1036
+
1037
+ def print_rust_code(expr, **settings):
1038
+ """Prints Rust representation of the given expression."""
1039
+ print(rust_code(expr, **settings))
shared/package-files/41/414ca861a10a75b05dddccaeaab88fbbe9e17639604f1b418166bd463e80fa93/_upsample_nearest_exact3d_cpu_dispatch.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API at::Tensor _upsample_nearest_exact3d(const at::Tensor & self, at::IntArrayRef output_size, ::std::optional<double> scales_d=::std::nullopt, ::std::optional<double> scales_h=::std::nullopt, ::std::optional<double> scales_w=::std::nullopt);
21
+ TORCH_API at::Tensor _upsample_nearest_exact3d_symint(const at::Tensor & self, c10::SymIntArrayRef output_size, ::std::optional<double> scales_d=::std::nullopt, ::std::optional<double> scales_h=::std::nullopt, ::std::optional<double> scales_w=::std::nullopt);
22
+ TORCH_API at::Tensor & _upsample_nearest_exact3d_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef output_size, ::std::optional<double> scales_d=::std::nullopt, ::std::optional<double> scales_h=::std::nullopt, ::std::optional<double> scales_w=::std::nullopt);
23
+ TORCH_API at::Tensor & _upsample_nearest_exact3d_outf(const at::Tensor & self, at::IntArrayRef output_size, ::std::optional<double> scales_d, ::std::optional<double> scales_h, ::std::optional<double> scales_w, at::Tensor & out);
24
+ TORCH_API at::Tensor & _upsample_nearest_exact3d_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef output_size, ::std::optional<double> scales_d=::std::nullopt, ::std::optional<double> scales_h=::std::nullopt, ::std::optional<double> scales_w=::std::nullopt);
25
+ TORCH_API at::Tensor & _upsample_nearest_exact3d_symint_outf(const at::Tensor & self, c10::SymIntArrayRef output_size, ::std::optional<double> scales_d, ::std::optional<double> scales_h, ::std::optional<double> scales_w, at::Tensor & out);
26
+
27
+ } // namespace cpu
28
+ } // namespace at
shared/package-files/41/414ec74c1ee8ff7eeaeeeac2c6f48b6171fa9a596fd2c52bd5ada631a035e60d/script-with-bom.cpython-311.pyc ADDED
Binary file (200 Bytes). View file
 
shared/package-files/41/414ed911448d0874dd3c1604a54d32949a9c9d2da2a19fff24fb3b349e91f07e/test_public_api.cpython-311.pyc ADDED
Binary file (19.5 kB). View file
 
shared/package-files/41/41539ec016af9995bc45a8df71481f41d1d3d649f39bdd64e8be3eb0b888a2a2/test_api.cpython-311.pyc ADDED
Binary file (25.5 kB). View file
 
shared/package-files/41/4153c68e57baad432b97f121708f3447dfe5cdbdd95cac85c2b2008f3bd1d49d/extending_distributions.cpython-311.pyc ADDED
Binary file (2.9 kB). View file
 
shared/package-files/41/415703c6edaaa239a93881cac0e4fc8fdfb958fb351561623fb2f2a553c0ff88/_analysis.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compatibility analyzer for PyTorch models."""
2
+
3
+ # mypy: allow-untyped-defs
4
+ # flake8: noqa: B950 We do not need flake8 as it complains line length
5
+ from __future__ import annotations
6
+
7
+ import dataclasses
8
+ import textwrap
9
+ import traceback
10
+ from collections import defaultdict
11
+ from typing import TYPE_CHECKING
12
+
13
+ import torch
14
+ import torch._export.serde.schema
15
+ from torch.export import graph_signature
16
+ from torch.onnx._internal.exporter import _dispatching, _registration
17
+
18
+
19
+ if TYPE_CHECKING:
20
+ import torch.fx
21
+
22
+
23
+ @dataclasses.dataclass
24
+ class ModelInfo:
25
+ """Information about the model."""
26
+
27
+ parameter_count: defaultdict[torch.dtype, int] = dataclasses.field(
28
+ default_factory=lambda: defaultdict(int)
29
+ )
30
+ buffer_count: defaultdict[torch.dtype, int] = dataclasses.field(
31
+ default_factory=lambda: defaultdict(int)
32
+ )
33
+ fx_node_count: int = 0
34
+ fx_node_op_count: defaultdict[str, int] = dataclasses.field(
35
+ default_factory=lambda: defaultdict(int)
36
+ )
37
+ fx_node_target_count: defaultdict[str, int] = dataclasses.field(
38
+ default_factory=lambda: defaultdict(int)
39
+ )
40
+ dispatch_failures: list[tuple[torch.fx.Node, str]] = dataclasses.field(
41
+ default_factory=list
42
+ )
43
+ inputs: dict[str, torch._export.serde.schema.TensorMeta] = dataclasses.field(
44
+ default_factory=dict
45
+ )
46
+ outputs: dict[str, torch._export.serde.schema.TensorMeta] = dataclasses.field(
47
+ default_factory=dict
48
+ )
49
+
50
+
51
+ def _count_weights(
52
+ exported_program: torch.export.ExportedProgram,
53
+ ) -> tuple[defaultdict[torch.dtype, int], defaultdict[torch.dtype, int]]:
54
+ """Count the size of the parameters in the exported program."""
55
+
56
+ parameter_count: defaultdict[torch.dtype, int] = defaultdict(int)
57
+ buffer_count: defaultdict[torch.dtype, int] = defaultdict(int)
58
+ for parameter in exported_program.parameters():
59
+ dtype = parameter.dtype
60
+ parameter_count[dtype] += parameter.numel()
61
+
62
+ for buffer in exported_program.buffers():
63
+ dtype = buffer.dtype
64
+ buffer_count[dtype] += buffer.numel()
65
+
66
+ return parameter_count, buffer_count
67
+
68
+
69
+ def _format_model_info(model_info: ModelInfo) -> str:
70
+ """Format the information about the model."""
71
+ lines = [
72
+ textwrap.dedent(
73
+ f"""\
74
+ PyTorch ONNX Conversion Analysis
75
+
76
+ ## Model Information
77
+
78
+ The model has {sum(model_info.parameter_count.values())} parameters and {sum(model_info.buffer_count.values())} buffers (non-trainable parameters).
79
+ Number of parameters per dtype:
80
+ ```python
81
+ {model_info.parameter_count}
82
+ ```
83
+ Number of buffers per dtype:
84
+ ```python
85
+ {model_info.buffer_count}
86
+ ```
87
+ """
88
+ ),
89
+ "Inputs:",
90
+ *[f"- `{name}`: `{meta}`" for name, meta in model_info.inputs.items()],
91
+ "",
92
+ "Outputs:",
93
+ *[f"- `{name}`: `{meta}`" for name, meta in model_info.outputs.items()],
94
+ "",
95
+ f"The FX graph has {model_info.fx_node_count} nodes in total. Number of FX nodes per op:",
96
+ ]
97
+ for op, count in model_info.fx_node_op_count.items():
98
+ lines.append(f"- `{op}`: {count}")
99
+ lines.append("\n")
100
+ lines.append("Of the call_function nodes, the counts of operators used are:\n")
101
+ sorted_targets = sorted(
102
+ model_info.fx_node_target_count.items(), key=lambda x: x[1], reverse=True
103
+ )
104
+ for target, count in sorted_targets:
105
+ lines.append(f"- `{target}`: {count}")
106
+
107
+ lines.append("")
108
+ lines.append("## ONNX Conversion Information")
109
+ lines.append("")
110
+
111
+ if model_info.dispatch_failures:
112
+ lines.append(
113
+ "The model contains operators the dispatcher could not find registered ONNX decompositions for. "
114
+ "This may be due to missing implementations, decompositions not registered "
115
+ "correctly, or a bug in the dispatcher."
116
+ )
117
+ lines.append("")
118
+ lines.append("Errors grouped by operator:\n")
119
+
120
+ target_to_nodes = defaultdict(list)
121
+ for node, _ in model_info.dispatch_failures:
122
+ target_to_nodes[str(node.target)].append(node)
123
+
124
+ target_to_messages = {}
125
+ for node, message in model_info.dispatch_failures:
126
+ if str(node.target) not in target_to_messages:
127
+ target_to_messages[str(node.target)] = message
128
+
129
+ for target, nodes in sorted(
130
+ target_to_nodes.items(), key=lambda x: x[0], reverse=True
131
+ ):
132
+ message = textwrap.indent(
133
+ f"{target_to_messages[target]}. Example node: `{nodes[0].format_node()}`. All nodes: `{nodes}`",
134
+ " ",
135
+ )
136
+ lines.append(f"- `{target}`: {message}")
137
+ else:
138
+ lines.append("All operators in the model have registered ONNX decompositions.")
139
+
140
+ return "\n".join(lines)
141
+
142
+
143
+ def _get_io_specs(exported_program: torch.export.ExportedProgram) -> tuple[dict, dict]:
144
+ """Get the input and output specs of the exported program."""
145
+
146
+ nodes: dict[str, torch.fx.Node] = {
147
+ node.name: node for node in exported_program.graph.nodes
148
+ }
149
+ user_inputs = [
150
+ spec
151
+ for spec in exported_program.graph_signature.input_specs
152
+ if spec.kind == graph_signature.InputKind.USER_INPUT
153
+ ]
154
+ user_outputs = [
155
+ spec
156
+ for spec in exported_program.graph_signature.output_specs
157
+ if spec.kind == graph_signature.OutputKind.USER_OUTPUT
158
+ ]
159
+ inputs: dict[str, torch._export.serde.schema.TensorMeta] = {}
160
+ outputs: dict[str, torch._export.serde.schema.TensorMeta] = {}
161
+ for spec in user_inputs:
162
+ if isinstance(spec.arg, graph_signature.ConstantArgument):
163
+ continue
164
+ name = spec.arg.name
165
+ # FIXME: tensor_meta is None sometimes when the exported program still knows the shape/type
166
+ inputs[name] = nodes[name].meta["tensor_meta"]
167
+ for spec in user_outputs:
168
+ if isinstance(spec.arg, graph_signature.ConstantArgument):
169
+ continue
170
+ name = spec.arg.name
171
+ outputs[name] = nodes[name].meta["tensor_meta"]
172
+ return inputs, outputs
173
+
174
+
175
+ def _count_fx_targets(
176
+ exported_program: torch.export.ExportedProgram,
177
+ ) -> defaultdict[str, int]:
178
+ """Count the number of targets for each node in the exported program."""
179
+ fx_node_target_count: defaultdict[str, int] = defaultdict(int)
180
+ for node in exported_program.graph.nodes:
181
+ if node.op == "call_function":
182
+ fx_node_target_count[str(node.target)] += 1
183
+ return fx_node_target_count
184
+
185
+
186
+ def analyze(
187
+ exported_program: torch.export.ExportedProgram,
188
+ registry: _registration.ONNXRegistry | None = None,
189
+ file=None,
190
+ ) -> None:
191
+ """Analyze the compatibility of the exported program."""
192
+ # Get basic information about the model
193
+ model_info = ModelInfo()
194
+ model_info.parameter_count, model_info.buffer_count = _count_weights(
195
+ exported_program
196
+ )
197
+ model_info.fx_node_count = len(exported_program.graph.nodes)
198
+ model_info.fx_node_target_count = _count_fx_targets(exported_program)
199
+ inputs, outputs = _get_io_specs(exported_program)
200
+ model_info.inputs = inputs
201
+ model_info.outputs = outputs
202
+
203
+ if registry is None:
204
+ registry = _registration.ONNXRegistry.from_torchlib()
205
+
206
+ # Try to find ops for every node in the graph
207
+ for node in exported_program.graph.nodes:
208
+ model_info.fx_node_op_count[node.op] += 1
209
+ if node.op == "call_function":
210
+ try:
211
+ onnx_function, message = _dispatching.dispatch(node, registry)
212
+ except Exception as e:
213
+ message = "Critical Error in dispatcher:\n"
214
+ formatted_exception = "\n".join(
215
+ traceback.format_exception(type(e), e, e.__traceback__)
216
+ )
217
+ message += f"```pytb\n{formatted_exception}\n```\n"
218
+ onnx_function = None
219
+ if onnx_function is None:
220
+ model_info.dispatch_failures.append((node, message))
221
+
222
+ # Print the results
223
+ report = _format_model_info(model_info)
224
+ print(report, file=file, flush=True)
225
+
226
+
227
+ def compare_ops(
228
+ program_a: torch.export.ExportedProgram, program_b: torch.export.ExportedProgram
229
+ ) -> tuple[set[str], set[str]]:
230
+ """Compare and get unique ops in two exported programs.
231
+
232
+ Args:
233
+ program_a: The first exported program.
234
+ program_b: The second exported program.
235
+
236
+ Returns:
237
+ A tuple of two sets, where the first set contains the unique ops in the first program
238
+ and the second set contains the unique ops in the second program.
239
+ """
240
+ program_a_ops = set(_count_fx_targets(program_a))
241
+ program_b_ops = set(_count_fx_targets(program_b))
242
+ return program_a_ops - program_b_ops, program_b_ops - program_a_ops
shared/package-files/41/41572ac50cf96b04496e676d8a6708898bb8e752e06dad34ed4c50c5d8f1fe40/_casefix.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Auto-generated by Tools/scripts/generate_re_casefix.py.
2
+
3
+ # Maps the code of lowercased character to codes of different lowercased
4
+ # characters which have the same uppercase.
5
+ _EXTRA_CASES = {
6
+ # LATIN SMALL LETTER I: LATIN SMALL LETTER DOTLESS I
7
+ 0x0069: (0x0131,), # 'i': 'ı'
8
+ # LATIN SMALL LETTER S: LATIN SMALL LETTER LONG S
9
+ 0x0073: (0x017f,), # 's': 'ſ'
10
+ # MICRO SIGN: GREEK SMALL LETTER MU
11
+ 0x00b5: (0x03bc,), # 'µ': 'μ'
12
+ # LATIN SMALL LETTER DOTLESS I: LATIN SMALL LETTER I
13
+ 0x0131: (0x0069,), # 'ı': 'i'
14
+ # LATIN SMALL LETTER LONG S: LATIN SMALL LETTER S
15
+ 0x017f: (0x0073,), # 'ſ': 's'
16
+ # COMBINING GREEK YPOGEGRAMMENI: GREEK SMALL LETTER IOTA, GREEK PROSGEGRAMMENI
17
+ 0x0345: (0x03b9, 0x1fbe), # '\u0345': 'ιι'
18
+ # GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS: GREEK SMALL LETTER IOTA WITH DIALYTIKA AND OXIA
19
+ 0x0390: (0x1fd3,), # 'ΐ': 'ΐ'
20
+ # GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS: GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND OXIA
21
+ 0x03b0: (0x1fe3,), # 'ΰ': 'ΰ'
22
+ # GREEK SMALL LETTER BETA: GREEK BETA SYMBOL
23
+ 0x03b2: (0x03d0,), # 'β': 'ϐ'
24
+ # GREEK SMALL LETTER EPSILON: GREEK LUNATE EPSILON SYMBOL
25
+ 0x03b5: (0x03f5,), # 'ε': 'ϵ'
26
+ # GREEK SMALL LETTER THETA: GREEK THETA SYMBOL
27
+ 0x03b8: (0x03d1,), # 'θ': 'ϑ'
28
+ # GREEK SMALL LETTER IOTA: COMBINING GREEK YPOGEGRAMMENI, GREEK PROSGEGRAMMENI
29
+ 0x03b9: (0x0345, 0x1fbe), # 'ι': '\u0345ι'
30
+ # GREEK SMALL LETTER KAPPA: GREEK KAPPA SYMBOL
31
+ 0x03ba: (0x03f0,), # 'κ': 'ϰ'
32
+ # GREEK SMALL LETTER MU: MICRO SIGN
33
+ 0x03bc: (0x00b5,), # 'μ': 'µ'
34
+ # GREEK SMALL LETTER PI: GREEK PI SYMBOL
35
+ 0x03c0: (0x03d6,), # 'π': 'ϖ'
36
+ # GREEK SMALL LETTER RHO: GREEK RHO SYMBOL
37
+ 0x03c1: (0x03f1,), # 'ρ': 'ϱ'
38
+ # GREEK SMALL LETTER FINAL SIGMA: GREEK SMALL LETTER SIGMA
39
+ 0x03c2: (0x03c3,), # 'ς': 'σ'
40
+ # GREEK SMALL LETTER SIGMA: GREEK SMALL LETTER FINAL SIGMA
41
+ 0x03c3: (0x03c2,), # 'σ': 'ς'
42
+ # GREEK SMALL LETTER PHI: GREEK PHI SYMBOL
43
+ 0x03c6: (0x03d5,), # 'φ': 'ϕ'
44
+ # GREEK BETA SYMBOL: GREEK SMALL LETTER BETA
45
+ 0x03d0: (0x03b2,), # 'ϐ': 'β'
46
+ # GREEK THETA SYMBOL: GREEK SMALL LETTER THETA
47
+ 0x03d1: (0x03b8,), # 'ϑ': 'θ'
48
+ # GREEK PHI SYMBOL: GREEK SMALL LETTER PHI
49
+ 0x03d5: (0x03c6,), # 'ϕ': 'φ'
50
+ # GREEK PI SYMBOL: GREEK SMALL LETTER PI
51
+ 0x03d6: (0x03c0,), # 'ϖ': 'π'
52
+ # GREEK KAPPA SYMBOL: GREEK SMALL LETTER KAPPA
53
+ 0x03f0: (0x03ba,), # 'ϰ': 'κ'
54
+ # GREEK RHO SYMBOL: GREEK SMALL LETTER RHO
55
+ 0x03f1: (0x03c1,), # 'ϱ': 'ρ'
56
+ # GREEK LUNATE EPSILON SYMBOL: GREEK SMALL LETTER EPSILON
57
+ 0x03f5: (0x03b5,), # 'ϵ': 'ε'
58
+ # CYRILLIC SMALL LETTER VE: CYRILLIC SMALL LETTER ROUNDED VE
59
+ 0x0432: (0x1c80,), # 'в': 'ᲀ'
60
+ # CYRILLIC SMALL LETTER DE: CYRILLIC SMALL LETTER LONG-LEGGED DE
61
+ 0x0434: (0x1c81,), # 'д': 'ᲁ'
62
+ # CYRILLIC SMALL LETTER O: CYRILLIC SMALL LETTER NARROW O
63
+ 0x043e: (0x1c82,), # 'о': 'ᲂ'
64
+ # CYRILLIC SMALL LETTER ES: CYRILLIC SMALL LETTER WIDE ES
65
+ 0x0441: (0x1c83,), # 'с': 'ᲃ'
66
+ # CYRILLIC SMALL LETTER TE: CYRILLIC SMALL LETTER TALL TE, CYRILLIC SMALL LETTER THREE-LEGGED TE
67
+ 0x0442: (0x1c84, 0x1c85), # 'т': 'ᲄᲅ'
68
+ # CYRILLIC SMALL LETTER HARD SIGN: CYRILLIC SMALL LETTER TALL HARD SIGN
69
+ 0x044a: (0x1c86,), # 'ъ': 'ᲆ'
70
+ # CYRILLIC SMALL LETTER YAT: CYRILLIC SMALL LETTER TALL YAT
71
+ 0x0463: (0x1c87,), # 'ѣ': 'ᲇ'
72
+ # CYRILLIC SMALL LETTER ROUNDED VE: CYRILLIC SMALL LETTER VE
73
+ 0x1c80: (0x0432,), # 'ᲀ': 'в'
74
+ # CYRILLIC SMALL LETTER LONG-LEGGED DE: CYRILLIC SMALL LETTER DE
75
+ 0x1c81: (0x0434,), # 'ᲁ': 'д'
76
+ # CYRILLIC SMALL LETTER NARROW O: CYRILLIC SMALL LETTER O
77
+ 0x1c82: (0x043e,), # 'ᲂ': 'о'
78
+ # CYRILLIC SMALL LETTER WIDE ES: CYRILLIC SMALL LETTER ES
79
+ 0x1c83: (0x0441,), # 'ᲃ': 'с'
80
+ # CYRILLIC SMALL LETTER TALL TE: CYRILLIC SMALL LETTER TE, CYRILLIC SMALL LETTER THREE-LEGGED TE
81
+ 0x1c84: (0x0442, 0x1c85), # 'ᲄ': 'тᲅ'
82
+ # CYRILLIC SMALL LETTER THREE-LEGGED TE: CYRILLIC SMALL LETTER TE, CYRILLIC SMALL LETTER TALL TE
83
+ 0x1c85: (0x0442, 0x1c84), # 'ᲅ': 'тᲄ'
84
+ # CYRILLIC SMALL LETTER TALL HARD SIGN: CYRILLIC SMALL LETTER HARD SIGN
85
+ 0x1c86: (0x044a,), # 'ᲆ': 'ъ'
86
+ # CYRILLIC SMALL LETTER TALL YAT: CYRILLIC SMALL LETTER YAT
87
+ 0x1c87: (0x0463,), # 'ᲇ': 'ѣ'
88
+ # CYRILLIC SMALL LETTER UNBLENDED UK: CYRILLIC SMALL LETTER MONOGRAPH UK
89
+ 0x1c88: (0xa64b,), # 'ᲈ': 'ꙋ'
90
+ # LATIN SMALL LETTER S WITH DOT ABOVE: LATIN SMALL LETTER LONG S WITH DOT ABOVE
91
+ 0x1e61: (0x1e9b,), # 'ṡ': 'ẛ'
92
+ # LATIN SMALL LETTER LONG S WITH DOT ABOVE: LATIN SMALL LETTER S WITH DOT ABOVE
93
+ 0x1e9b: (0x1e61,), # 'ẛ': 'ṡ'
94
+ # GREEK PROSGEGRAMMENI: COMBINING GREEK YPOGEGRAMMENI, GREEK SMALL LETTER IOTA
95
+ 0x1fbe: (0x0345, 0x03b9), # 'ι': '\u0345ι'
96
+ # GREEK SMALL LETTER IOTA WITH DIALYTIKA AND OXIA: GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
97
+ 0x1fd3: (0x0390,), # 'ΐ': 'ΐ'
98
+ # GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND OXIA: GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
99
+ 0x1fe3: (0x03b0,), # 'ΰ': 'ΰ'
100
+ # CYRILLIC SMALL LETTER MONOGRAPH UK: CYRILLIC SMALL LETTER UNBLENDED UK
101
+ 0xa64b: (0x1c88,), # 'ꙋ': 'ᲈ'
102
+ # LATIN SMALL LIGATURE LONG S T: LATIN SMALL LIGATURE ST
103
+ 0xfb05: (0xfb06,), # 'ſt': 'st'
104
+ # LATIN SMALL LIGATURE ST: LATIN SMALL LIGATURE LONG S T
105
+ 0xfb06: (0xfb05,), # 'st': 'ſt'
106
+ }
shared/package-files/41/41572cc508b286773cb8b3c20161918a6971c4138e633e6cfe3f342c15337d8b/quantized_batch_norm.h ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+ #include <string_view>
18
+
19
+
20
+
21
+ #include <ATen/ops/quantized_batch_norm_ops.h>
22
+
23
+ namespace at {
24
+
25
+
26
+ // aten::quantized_batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor mean, Tensor var, float eps, float output_scale, int output_zero_point) -> Tensor
27
+ inline at::Tensor quantized_batch_norm(const at::Tensor & input, const ::std::optional<at::Tensor> & weight, const ::std::optional<at::Tensor> & bias, const at::Tensor & mean, const at::Tensor & var, double eps, double output_scale, int64_t output_zero_point) {
28
+ return at::_ops::quantized_batch_norm::call(input, weight, bias, mean, var, eps, output_scale, output_zero_point);
29
+ }
30
+
31
+ // aten::quantized_batch_norm.out(Tensor input, Tensor? weight, Tensor? bias, Tensor mean, Tensor var, float eps, float output_scale, int output_zero_point, *, Tensor(a!) out) -> Tensor(a!)
32
+ inline at::Tensor & quantized_batch_norm_out(at::Tensor & out, const at::Tensor & input, const ::std::optional<at::Tensor> & weight, const ::std::optional<at::Tensor> & bias, const at::Tensor & mean, const at::Tensor & var, double eps, double output_scale, int64_t output_zero_point) {
33
+ return at::_ops::quantized_batch_norm_out::call(input, weight, bias, mean, var, eps, output_scale, output_zero_point, out);
34
+ }
35
+ // aten::quantized_batch_norm.out(Tensor input, Tensor? weight, Tensor? bias, Tensor mean, Tensor var, float eps, float output_scale, int output_zero_point, *, Tensor(a!) out) -> Tensor(a!)
36
+ inline at::Tensor & quantized_batch_norm_outf(const at::Tensor & input, const ::std::optional<at::Tensor> & weight, const ::std::optional<at::Tensor> & bias, const at::Tensor & mean, const at::Tensor & var, double eps, double output_scale, int64_t output_zero_point, at::Tensor & out) {
37
+ return at::_ops::quantized_batch_norm_out::call(input, weight, bias, mean, var, eps, output_scale, output_zero_point, out);
38
+ }
39
+
40
+ }
shared/package-files/41/415b0de31cdcfae837bcf8ea4fbb056c6a0871e322b9362b62d4b84d8f79fb92/arrayop.cpython-311.pyc ADDED
Binary file (25.3 kB). View file
 
shared/package-files/41/415cdc1afe4e2e8c659620d48843cc32c11e42174b9c4d50bad3fc71a3b9083f/random.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from collections.abc import Iterable
3
+ from typing import Union
4
+
5
+ import torch
6
+ from torch import Tensor
7
+
8
+ from . import _lazy_call, _lazy_init, current_device, device_count
9
+
10
+
11
+ __all__ = [
12
+ "get_rng_state",
13
+ "get_rng_state_all",
14
+ "set_rng_state",
15
+ "set_rng_state_all",
16
+ "manual_seed",
17
+ "manual_seed_all",
18
+ "seed",
19
+ "seed_all",
20
+ "initial_seed",
21
+ ]
22
+
23
+
24
+ def get_rng_state(device: Union[int, str, torch.device] = "cuda") -> Tensor:
25
+ r"""Return the random number generator state of the specified GPU as a ByteTensor.
26
+
27
+ Args:
28
+ device (torch.device or int, optional): The device to return the RNG state of.
29
+ Default: ``'cuda'`` (i.e., ``torch.device('cuda')``, the current CUDA device).
30
+
31
+ .. warning::
32
+ This function eagerly initializes CUDA.
33
+ """
34
+ _lazy_init()
35
+ if isinstance(device, str):
36
+ device = torch.device(device)
37
+ elif isinstance(device, int):
38
+ device = torch.device("cuda", device)
39
+ idx = device.index
40
+ if idx is None:
41
+ idx = current_device()
42
+ default_generator = torch.cuda.default_generators[idx]
43
+ return default_generator.get_state()
44
+
45
+
46
+ def get_rng_state_all() -> list[Tensor]:
47
+ r"""Return a list of ByteTensor representing the random number states of all devices."""
48
+ results = [get_rng_state(i) for i in range(device_count())]
49
+ return results
50
+
51
+
52
+ def set_rng_state(
53
+ new_state: Tensor, device: Union[int, str, torch.device] = "cuda"
54
+ ) -> None:
55
+ r"""Set the random number generator state of the specified GPU.
56
+
57
+ Args:
58
+ new_state (torch.ByteTensor): The desired state
59
+ device (torch.device or int, optional): The device to set the RNG state.
60
+ Default: ``'cuda'`` (i.e., ``torch.device('cuda')``, the current CUDA device).
61
+ """
62
+ with torch._C._DisableFuncTorch():
63
+ new_state_copy = new_state.clone(memory_format=torch.contiguous_format)
64
+ if isinstance(device, str):
65
+ device = torch.device(device)
66
+ elif isinstance(device, int):
67
+ device = torch.device("cuda", device)
68
+
69
+ def cb():
70
+ idx = device.index
71
+ if idx is None:
72
+ idx = current_device()
73
+ default_generator = torch.cuda.default_generators[idx]
74
+ default_generator.set_state(new_state_copy)
75
+
76
+ _lazy_call(cb)
77
+
78
+
79
+ def set_rng_state_all(new_states: Iterable[Tensor]) -> None:
80
+ r"""Set the random number generator state of all devices.
81
+
82
+ Args:
83
+ new_states (Iterable of torch.ByteTensor): The desired state for each device.
84
+ """
85
+ for i, state in enumerate(new_states):
86
+ set_rng_state(state, i)
87
+
88
+
89
+ def manual_seed(seed: int) -> None:
90
+ r"""Set the seed for generating random numbers for the current GPU.
91
+
92
+ It's safe to call this function if CUDA is not available; in that
93
+ case, it is silently ignored.
94
+
95
+ Args:
96
+ seed (int): The desired seed.
97
+
98
+ .. warning::
99
+ If you are working with a multi-GPU model, this function is insufficient
100
+ to get determinism. To seed all GPUs, use :func:`manual_seed_all`.
101
+ """
102
+ seed = int(seed)
103
+
104
+ def cb():
105
+ idx = current_device()
106
+ default_generator = torch.cuda.default_generators[idx]
107
+ default_generator.manual_seed(seed)
108
+
109
+ _lazy_call(cb, seed=True)
110
+
111
+
112
+ def manual_seed_all(seed: int) -> None:
113
+ r"""Set the seed for generating random numbers on all GPUs.
114
+
115
+ It's safe to call this function if CUDA is not available; in that
116
+ case, it is silently ignored.
117
+
118
+ Args:
119
+ seed (int): The desired seed.
120
+ """
121
+ seed = int(seed)
122
+
123
+ def cb():
124
+ for i in range(device_count()):
125
+ default_generator = torch.cuda.default_generators[i]
126
+ default_generator.manual_seed(seed)
127
+
128
+ _lazy_call(cb, seed_all=True)
129
+
130
+
131
+ def seed() -> None:
132
+ r"""Set the seed for generating random numbers to a random number for the current GPU.
133
+
134
+ It's safe to call this function if CUDA is not available; in that
135
+ case, it is silently ignored.
136
+
137
+ .. warning::
138
+ If you are working with a multi-GPU model, this function will only initialize
139
+ the seed on one GPU. To initialize all GPUs, use :func:`seed_all`.
140
+ """
141
+
142
+ def cb():
143
+ idx = current_device()
144
+ default_generator = torch.cuda.default_generators[idx]
145
+ default_generator.seed()
146
+
147
+ _lazy_call(cb)
148
+
149
+
150
+ def seed_all() -> None:
151
+ r"""Set the seed for generating random numbers to a random number on all GPUs.
152
+
153
+ It's safe to call this function if CUDA is not available; in that
154
+ case, it is silently ignored.
155
+ """
156
+
157
+ def cb():
158
+ random_seed = 0
159
+ seeded = False
160
+ for i in range(device_count()):
161
+ default_generator = torch.cuda.default_generators[i]
162
+ if not seeded:
163
+ default_generator.seed()
164
+ random_seed = default_generator.initial_seed()
165
+ seeded = True
166
+ else:
167
+ default_generator.manual_seed(random_seed)
168
+
169
+ _lazy_call(cb)
170
+
171
+
172
+ def initial_seed() -> int:
173
+ r"""Return the current random seed of the current GPU.
174
+
175
+ .. warning::
176
+ This function eagerly initializes CUDA.
177
+ """
178
+ _lazy_init()
179
+ idx = current_device()
180
+ default_generator = torch.cuda.default_generators[idx]
181
+ return default_generator.initial_seed()
shared/package-files/41/416494ee611cf9890b4697912f2e99b7daf78fcc011205656ecd243a29652a04/subclass_parametrization.cpython-311.pyc ADDED
Binary file (5.71 kB). View file
 
shared/package-files/41/416888499fadfed2fe45d7ac4c27bf11076550cd1e7d6be99f8e6b90c01a1ddb/choose_qparams_optimized_native.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor> choose_qparams_optimized(const at::Tensor & input, int64_t numel, int64_t n_bins, double ratio, int64_t bit_width);
20
+ } // namespace native
21
+ } // namespace at
shared/package-files/41/416cda72c316ec5b646ac62fb19f56a9113106368caacc474070f9b58b190450/conv_relu.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from torch.ao.nn.intrinsic.quantized import ConvReLU1d, ConvReLU2d, ConvReLU3d
2
+
3
+
4
+ __all__ = [
5
+ "ConvReLU1d",
6
+ "ConvReLU2d",
7
+ "ConvReLU3d",
8
+ ]
shared/package-files/41/41703b13df5086b125aed6ea643965701e86f26522fa04f520191c0b5c0a5010/_arrow_string_mixins.cpython-311.pyc ADDED
Binary file (5.14 kB). View file
 
shared/package-files/41/41733bee0b435a924f09b0d6fd085c0159f2fde59c54b11bb44e211a4d8244a2/_functional_assert_scalar_ops.h ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <string_view>
6
+ #include <tuple>
7
+ #include <vector>
8
+
9
+ // Forward declarations of any types needed in the operator signatures.
10
+ // We can't directly include these classes because it will cause circular include dependencies.
11
+ // This file is included by TensorBody.h, which defines the Tensor class.
12
+ #include <ATen/core/ATen_fwd.h>
13
+
14
+ namespace at {
15
+ namespace _ops {
16
+
17
+
18
+ struct TORCH_API _functional_assert_scalar {
19
+ using schema = at::Tensor (const at::Scalar &, c10::string_view, const at::Tensor &);
20
+ using ptr_schema = schema*;
21
+ // See Note [static constexpr char* members for windows NVCC]
22
+ static constexpr const char* name = "aten::_functional_assert_scalar";
23
+ static constexpr const char* overload_name = "";
24
+ static constexpr const char* schema_str = "_functional_assert_scalar(Scalar self, str assert_msg, Tensor dep_token) -> Tensor";
25
+ static at::Tensor call(const at::Scalar & self, c10::string_view assert_msg, const at::Tensor & dep_token);
26
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Scalar & self, c10::string_view assert_msg, const at::Tensor & dep_token);
27
+ };
28
+
29
+ }} // namespace at::_ops
shared/package-files/41/4174e71f63cce4b8834669601c92888e99b2e00092b840a8f8ee8720b807f293/ReduceOps.h ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ namespace at {
3
+ struct TensorIterator;
4
+ }
5
+
6
+ namespace c10 {
7
+ class Scalar;
8
+ }
9
+
10
+ namespace at::native {
11
+
12
+ void norm_launch_kernel(TensorIterator &iter, double val);
13
+ void min_launch_kernel(TensorIterator &iter);
14
+ void max_launch_kernel(TensorIterator &iter);
15
+ void aminmax_launch_kernel(TensorIterator &iter);
16
+ void min_all_launch_kernel(TensorIterator &iter);
17
+ void max_all_launch_kernel(TensorIterator &iter);
18
+ void aminmax_allreduce_launch_kernel(TensorIterator &iter);
19
+
20
+ } // namespace at::native
shared/package-files/41/41760d83887db0c5612d20cec9a893908bff91f7ca948e1858855a8639ab8354/test_solvers.cpython-311.pyc ADDED
Binary file (85.6 kB). View file
 
shared/package-files/41/417696b7aa221ecfbc25e2ab9d43ebea88d33baf31d91d1bca393974a5917a91/agent_utils.h ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/distributed/c10d/PrefixStore.hpp>
4
+ #include <torch/csrc/distributed/rpc/utils.h>
5
+
6
+ namespace torch::distributed::rpc {
7
+
8
+ // All RPC peers should call into this function at the same time. Each peer
9
+ // provides its own id and name, and this function uses the given Store to
10
+ // gather global name-to-id mapping on all peers.
11
+ TORCH_API std::unordered_map<std::string, worker_id_t> collectNames(
12
+ ::c10d::PrefixStore store,
13
+ const worker_id_t selfId,
14
+ const std::string& selfName,
15
+ const int worldSize);
16
+
17
+ // Ranks in dynamic RPC groups will initially call into this to establish the
18
+ // name-to-id mapping for the current peers in the group. The current rank will
19
+ // put its own worker info in the store and discover all the ranks that came
20
+ // before it. NOTE: This needs to be called with the Dynamic RPC group
21
+ // membership management token held.
22
+ TORCH_API std::unordered_map<std::string, worker_id_t> collectCurrentNames(
23
+ ::c10d::PrefixStore store,
24
+ const worker_id_t selfId,
25
+ const std::string& selfName);
26
+
27
+ // Remove name frmo Store, used in dynamic RPC groups.
28
+ // NOTE: This needs to be called with the Dynamic RPC group
29
+ // membership management token held.
30
+ TORCH_API void removeCurrentName(
31
+ ::c10d::PrefixStore store,
32
+ const worker_id_t selfId,
33
+ const std::string& selfName);
34
+
35
+ // This performs a synchronization of all call counts by using store.
36
+ // All RPC peers wait for others to join to exit at the same time.
37
+ TORCH_API int syncCallCount(
38
+ ::c10d::PrefixStore store,
39
+ const int worldSize,
40
+ int activeCalls = 0);
41
+
42
+ } // namespace torch::distributed::rpc
shared/package-files/41/417826f08df4a690975d36ec53ad6ecbfe7b3dbf9ee4da572c94e257ee27a5aa/test_matching.cpython-311.pyc ADDED
Binary file (32.1 kB). View file
 
shared/package-files/41/41874553df0d7b5da2b206d102f59ccf6c29bdee40e70fdc15f2cac31525d000/test_parenmatch.cpython-311.pyc ADDED
Binary file (7.24 kB). View file
 
shared/package-files/41/418a9296e5619b1abf0406a010a05be9e248b1e14503078c8e9b8b80d3cc5162/test_codegen_julia.py ADDED
@@ -0,0 +1,620 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from io import StringIO
2
+
3
+ from sympy.core import S, symbols, Eq, pi, Catalan, EulerGamma, Function
4
+ from sympy.core.relational import Equality
5
+ from sympy.functions.elementary.piecewise import Piecewise
6
+ from sympy.matrices import Matrix, MatrixSymbol
7
+ from sympy.utilities.codegen import JuliaCodeGen, codegen, make_routine
8
+ from sympy.testing.pytest import XFAIL
9
+ import sympy
10
+
11
+
12
+ x, y, z = symbols('x,y,z')
13
+
14
+
15
+ def test_empty_jl_code():
16
+ code_gen = JuliaCodeGen()
17
+ output = StringIO()
18
+ code_gen.dump_jl([], output, "file", header=False, empty=False)
19
+ source = output.getvalue()
20
+ assert source == ""
21
+
22
+
23
+ def test_jl_simple_code():
24
+ name_expr = ("test", (x + y)*z)
25
+ result, = codegen(name_expr, "Julia", header=False, empty=False)
26
+ assert result[0] == "test.jl"
27
+ source = result[1]
28
+ expected = (
29
+ "function test(x, y, z)\n"
30
+ " out1 = z .* (x + y)\n"
31
+ " return out1\n"
32
+ "end\n"
33
+ )
34
+ assert source == expected
35
+
36
+
37
+ def test_jl_simple_code_with_header():
38
+ name_expr = ("test", (x + y)*z)
39
+ result, = codegen(name_expr, "Julia", header=True, empty=False)
40
+ assert result[0] == "test.jl"
41
+ source = result[1]
42
+ expected = (
43
+ "# Code generated with SymPy " + sympy.__version__ + "\n"
44
+ "#\n"
45
+ "# See http://www.sympy.org/ for more information.\n"
46
+ "#\n"
47
+ "# This file is part of 'project'\n"
48
+ "function test(x, y, z)\n"
49
+ " out1 = z .* (x + y)\n"
50
+ " return out1\n"
51
+ "end\n"
52
+ )
53
+ assert source == expected
54
+
55
+
56
+ def test_jl_simple_code_nameout():
57
+ expr = Equality(z, (x + y))
58
+ name_expr = ("test", expr)
59
+ result, = codegen(name_expr, "Julia", header=False, empty=False)
60
+ source = result[1]
61
+ expected = (
62
+ "function test(x, y)\n"
63
+ " z = x + y\n"
64
+ " return z\n"
65
+ "end\n"
66
+ )
67
+ assert source == expected
68
+
69
+
70
+ def test_jl_numbersymbol():
71
+ name_expr = ("test", pi**Catalan)
72
+ result, = codegen(name_expr, "Julia", header=False, empty=False)
73
+ source = result[1]
74
+ expected = (
75
+ "function test()\n"
76
+ " out1 = pi ^ catalan\n"
77
+ " return out1\n"
78
+ "end\n"
79
+ )
80
+ assert source == expected
81
+
82
+
83
+ @XFAIL
84
+ def test_jl_numbersymbol_no_inline():
85
+ # FIXME: how to pass inline=False to the JuliaCodePrinter?
86
+ name_expr = ("test", [pi**Catalan, EulerGamma])
87
+ result, = codegen(name_expr, "Julia", header=False,
88
+ empty=False, inline=False)
89
+ source = result[1]
90
+ expected = (
91
+ "function test()\n"
92
+ " Catalan = 0.915965594177219\n"
93
+ " EulerGamma = 0.5772156649015329\n"
94
+ " out1 = pi ^ Catalan\n"
95
+ " out2 = EulerGamma\n"
96
+ " return out1, out2\n"
97
+ "end\n"
98
+ )
99
+ assert source == expected
100
+
101
+
102
+ def test_jl_code_argument_order():
103
+ expr = x + y
104
+ routine = make_routine("test", expr, argument_sequence=[z, x, y], language="julia")
105
+ code_gen = JuliaCodeGen()
106
+ output = StringIO()
107
+ code_gen.dump_jl([routine], output, "test", header=False, empty=False)
108
+ source = output.getvalue()
109
+ expected = (
110
+ "function test(z, x, y)\n"
111
+ " out1 = x + y\n"
112
+ " return out1\n"
113
+ "end\n"
114
+ )
115
+ assert source == expected
116
+
117
+
118
+ def test_multiple_results_m():
119
+ # Here the output order is the input order
120
+ expr1 = (x + y)*z
121
+ expr2 = (x - y)*z
122
+ name_expr = ("test", [expr1, expr2])
123
+ result, = codegen(name_expr, "Julia", header=False, empty=False)
124
+ source = result[1]
125
+ expected = (
126
+ "function test(x, y, z)\n"
127
+ " out1 = z .* (x + y)\n"
128
+ " out2 = z .* (x - y)\n"
129
+ " return out1, out2\n"
130
+ "end\n"
131
+ )
132
+ assert source == expected
133
+
134
+
135
+ def test_results_named_unordered():
136
+ # Here output order is based on name_expr
137
+ A, B, C = symbols('A,B,C')
138
+ expr1 = Equality(C, (x + y)*z)
139
+ expr2 = Equality(A, (x - y)*z)
140
+ expr3 = Equality(B, 2*x)
141
+ name_expr = ("test", [expr1, expr2, expr3])
142
+ result, = codegen(name_expr, "Julia", header=False, empty=False)
143
+ source = result[1]
144
+ expected = (
145
+ "function test(x, y, z)\n"
146
+ " C = z .* (x + y)\n"
147
+ " A = z .* (x - y)\n"
148
+ " B = 2 * x\n"
149
+ " return C, A, B\n"
150
+ "end\n"
151
+ )
152
+ assert source == expected
153
+
154
+
155
+ def test_results_named_ordered():
156
+ A, B, C = symbols('A,B,C')
157
+ expr1 = Equality(C, (x + y)*z)
158
+ expr2 = Equality(A, (x - y)*z)
159
+ expr3 = Equality(B, 2*x)
160
+ name_expr = ("test", [expr1, expr2, expr3])
161
+ result = codegen(name_expr, "Julia", header=False, empty=False,
162
+ argument_sequence=(x, z, y))
163
+ assert result[0][0] == "test.jl"
164
+ source = result[0][1]
165
+ expected = (
166
+ "function test(x, z, y)\n"
167
+ " C = z .* (x + y)\n"
168
+ " A = z .* (x - y)\n"
169
+ " B = 2 * x\n"
170
+ " return C, A, B\n"
171
+ "end\n"
172
+ )
173
+ assert source == expected
174
+
175
+
176
+ def test_complicated_jl_codegen():
177
+ from sympy.functions.elementary.trigonometric import (cos, sin, tan)
178
+ name_expr = ("testlong",
179
+ [ ((sin(x) + cos(y) + tan(z))**3).expand(),
180
+ cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))
181
+ ])
182
+ result = codegen(name_expr, "Julia", header=False, empty=False)
183
+ assert result[0][0] == "testlong.jl"
184
+ source = result[0][1]
185
+ expected = (
186
+ "function testlong(x, y, z)\n"
187
+ " out1 = sin(x) .^ 3 + 3 * sin(x) .^ 2 .* cos(y) + 3 * sin(x) .^ 2 .* tan(z)"
188
+ " + 3 * sin(x) .* cos(y) .^ 2 + 6 * sin(x) .* cos(y) .* tan(z) + 3 * sin(x) .* tan(z) .^ 2"
189
+ " + cos(y) .^ 3 + 3 * cos(y) .^ 2 .* tan(z) + 3 * cos(y) .* tan(z) .^ 2 + tan(z) .^ 3\n"
190
+ " out2 = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))\n"
191
+ " return out1, out2\n"
192
+ "end\n"
193
+ )
194
+ assert source == expected
195
+
196
+
197
+ def test_jl_output_arg_mixed_unordered():
198
+ # named outputs are alphabetical, unnamed output appear in the given order
199
+ from sympy.functions.elementary.trigonometric import (cos, sin)
200
+ a = symbols("a")
201
+ name_expr = ("foo", [cos(2*x), Equality(y, sin(x)), cos(x), Equality(a, sin(2*x))])
202
+ result, = codegen(name_expr, "Julia", header=False, empty=False)
203
+ assert result[0] == "foo.jl"
204
+ source = result[1]
205
+ expected = (
206
+ 'function foo(x)\n'
207
+ ' out1 = cos(2 * x)\n'
208
+ ' y = sin(x)\n'
209
+ ' out3 = cos(x)\n'
210
+ ' a = sin(2 * x)\n'
211
+ ' return out1, y, out3, a\n'
212
+ 'end\n'
213
+ )
214
+ assert source == expected
215
+
216
+
217
+ def test_jl_piecewise_():
218
+ pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True), evaluate=False)
219
+ name_expr = ("pwtest", pw)
220
+ result, = codegen(name_expr, "Julia", header=False, empty=False)
221
+ source = result[1]
222
+ expected = (
223
+ "function pwtest(x)\n"
224
+ " out1 = ((x < -1) ? (0) :\n"
225
+ " (x <= 1) ? (x .^ 2) :\n"
226
+ " (x > 1) ? (2 - x) : (1))\n"
227
+ " return out1\n"
228
+ "end\n"
229
+ )
230
+ assert source == expected
231
+
232
+
233
+ @XFAIL
234
+ def test_jl_piecewise_no_inline():
235
+ # FIXME: how to pass inline=False to the JuliaCodePrinter?
236
+ pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True))
237
+ name_expr = ("pwtest", pw)
238
+ result, = codegen(name_expr, "Julia", header=False, empty=False,
239
+ inline=False)
240
+ source = result[1]
241
+ expected = (
242
+ "function pwtest(x)\n"
243
+ " if (x < -1)\n"
244
+ " out1 = 0\n"
245
+ " elseif (x <= 1)\n"
246
+ " out1 = x .^ 2\n"
247
+ " elseif (x > 1)\n"
248
+ " out1 = -x + 2\n"
249
+ " else\n"
250
+ " out1 = 1\n"
251
+ " end\n"
252
+ " return out1\n"
253
+ "end\n"
254
+ )
255
+ assert source == expected
256
+
257
+
258
+ def test_jl_multifcns_per_file():
259
+ name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
260
+ result = codegen(name_expr, "Julia", header=False, empty=False)
261
+ assert result[0][0] == "foo.jl"
262
+ source = result[0][1]
263
+ expected = (
264
+ "function foo(x, y)\n"
265
+ " out1 = 2 * x\n"
266
+ " out2 = 3 * y\n"
267
+ " return out1, out2\n"
268
+ "end\n"
269
+ "function bar(y)\n"
270
+ " out1 = y .^ 2\n"
271
+ " out2 = 4 * y\n"
272
+ " return out1, out2\n"
273
+ "end\n"
274
+ )
275
+ assert source == expected
276
+
277
+
278
+ def test_jl_multifcns_per_file_w_header():
279
+ name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
280
+ result = codegen(name_expr, "Julia", header=True, empty=False)
281
+ assert result[0][0] == "foo.jl"
282
+ source = result[0][1]
283
+ expected = (
284
+ "# Code generated with SymPy " + sympy.__version__ + "\n"
285
+ "#\n"
286
+ "# See http://www.sympy.org/ for more information.\n"
287
+ "#\n"
288
+ "# This file is part of 'project'\n"
289
+ "function foo(x, y)\n"
290
+ " out1 = 2 * x\n"
291
+ " out2 = 3 * y\n"
292
+ " return out1, out2\n"
293
+ "end\n"
294
+ "function bar(y)\n"
295
+ " out1 = y .^ 2\n"
296
+ " out2 = 4 * y\n"
297
+ " return out1, out2\n"
298
+ "end\n"
299
+ )
300
+ assert source == expected
301
+
302
+
303
+ def test_jl_filename_match_prefix():
304
+ name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
305
+ result, = codegen(name_expr, "Julia", prefix="baz", header=False,
306
+ empty=False)
307
+ assert result[0] == "baz.jl"
308
+
309
+
310
+ def test_jl_matrix_named():
311
+ e2 = Matrix([[x, 2*y, pi*z]])
312
+ name_expr = ("test", Equality(MatrixSymbol('myout1', 1, 3), e2))
313
+ result = codegen(name_expr, "Julia", header=False, empty=False)
314
+ assert result[0][0] == "test.jl"
315
+ source = result[0][1]
316
+ expected = (
317
+ "function test(x, y, z)\n"
318
+ " myout1 = [x 2 * y pi * z]\n"
319
+ " return myout1\n"
320
+ "end\n"
321
+ )
322
+ assert source == expected
323
+
324
+
325
+ def test_jl_matrix_named_matsym():
326
+ myout1 = MatrixSymbol('myout1', 1, 3)
327
+ e2 = Matrix([[x, 2*y, pi*z]])
328
+ name_expr = ("test", Equality(myout1, e2, evaluate=False))
329
+ result, = codegen(name_expr, "Julia", header=False, empty=False)
330
+ source = result[1]
331
+ expected = (
332
+ "function test(x, y, z)\n"
333
+ " myout1 = [x 2 * y pi * z]\n"
334
+ " return myout1\n"
335
+ "end\n"
336
+ )
337
+ assert source == expected
338
+
339
+
340
+ def test_jl_matrix_output_autoname():
341
+ expr = Matrix([[x, x+y, 3]])
342
+ name_expr = ("test", expr)
343
+ result, = codegen(name_expr, "Julia", header=False, empty=False)
344
+ source = result[1]
345
+ expected = (
346
+ "function test(x, y)\n"
347
+ " out1 = [x x + y 3]\n"
348
+ " return out1\n"
349
+ "end\n"
350
+ )
351
+ assert source == expected
352
+
353
+
354
+ def test_jl_matrix_output_autoname_2():
355
+ e1 = (x + y)
356
+ e2 = Matrix([[2*x, 2*y, 2*z]])
357
+ e3 = Matrix([[x], [y], [z]])
358
+ e4 = Matrix([[x, y], [z, 16]])
359
+ name_expr = ("test", (e1, e2, e3, e4))
360
+ result, = codegen(name_expr, "Julia", header=False, empty=False)
361
+ source = result[1]
362
+ expected = (
363
+ "function test(x, y, z)\n"
364
+ " out1 = x + y\n"
365
+ " out2 = [2 * x 2 * y 2 * z]\n"
366
+ " out3 = [x, y, z]\n"
367
+ " out4 = [x y;\n"
368
+ " z 16]\n"
369
+ " return out1, out2, out3, out4\n"
370
+ "end\n"
371
+ )
372
+ assert source == expected
373
+
374
+
375
+ def test_jl_results_matrix_named_ordered():
376
+ B, C = symbols('B,C')
377
+ A = MatrixSymbol('A', 1, 3)
378
+ expr1 = Equality(C, (x + y)*z)
379
+ expr2 = Equality(A, Matrix([[1, 2, x]]))
380
+ expr3 = Equality(B, 2*x)
381
+ name_expr = ("test", [expr1, expr2, expr3])
382
+ result, = codegen(name_expr, "Julia", header=False, empty=False,
383
+ argument_sequence=(x, z, y))
384
+ source = result[1]
385
+ expected = (
386
+ "function test(x, z, y)\n"
387
+ " C = z .* (x + y)\n"
388
+ " A = [1 2 x]\n"
389
+ " B = 2 * x\n"
390
+ " return C, A, B\n"
391
+ "end\n"
392
+ )
393
+ assert source == expected
394
+
395
+
396
+ def test_jl_matrixsymbol_slice():
397
+ A = MatrixSymbol('A', 2, 3)
398
+ B = MatrixSymbol('B', 1, 3)
399
+ C = MatrixSymbol('C', 1, 3)
400
+ D = MatrixSymbol('D', 2, 1)
401
+ name_expr = ("test", [Equality(B, A[0, :]),
402
+ Equality(C, A[1, :]),
403
+ Equality(D, A[:, 2])])
404
+ result, = codegen(name_expr, "Julia", header=False, empty=False)
405
+ source = result[1]
406
+ expected = (
407
+ "function test(A)\n"
408
+ " B = A[1,:]\n"
409
+ " C = A[2,:]\n"
410
+ " D = A[:,3]\n"
411
+ " return B, C, D\n"
412
+ "end\n"
413
+ )
414
+ assert source == expected
415
+
416
+
417
+ def test_jl_matrixsymbol_slice2():
418
+ A = MatrixSymbol('A', 3, 4)
419
+ B = MatrixSymbol('B', 2, 2)
420
+ C = MatrixSymbol('C', 2, 2)
421
+ name_expr = ("test", [Equality(B, A[0:2, 0:2]),
422
+ Equality(C, A[0:2, 1:3])])
423
+ result, = codegen(name_expr, "Julia", header=False, empty=False)
424
+ source = result[1]
425
+ expected = (
426
+ "function test(A)\n"
427
+ " B = A[1:2,1:2]\n"
428
+ " C = A[1:2,2:3]\n"
429
+ " return B, C\n"
430
+ "end\n"
431
+ )
432
+ assert source == expected
433
+
434
+
435
+ def test_jl_matrixsymbol_slice3():
436
+ A = MatrixSymbol('A', 8, 7)
437
+ B = MatrixSymbol('B', 2, 2)
438
+ C = MatrixSymbol('C', 4, 2)
439
+ name_expr = ("test", [Equality(B, A[6:, 1::3]),
440
+ Equality(C, A[::2, ::3])])
441
+ result, = codegen(name_expr, "Julia", header=False, empty=False)
442
+ source = result[1]
443
+ expected = (
444
+ "function test(A)\n"
445
+ " B = A[7:end,2:3:end]\n"
446
+ " C = A[1:2:end,1:3:end]\n"
447
+ " return B, C\n"
448
+ "end\n"
449
+ )
450
+ assert source == expected
451
+
452
+
453
+ def test_jl_matrixsymbol_slice_autoname():
454
+ A = MatrixSymbol('A', 2, 3)
455
+ B = MatrixSymbol('B', 1, 3)
456
+ name_expr = ("test", [Equality(B, A[0,:]), A[1,:], A[:,0], A[:,1]])
457
+ result, = codegen(name_expr, "Julia", header=False, empty=False)
458
+ source = result[1]
459
+ expected = (
460
+ "function test(A)\n"
461
+ " B = A[1,:]\n"
462
+ " out2 = A[2,:]\n"
463
+ " out3 = A[:,1]\n"
464
+ " out4 = A[:,2]\n"
465
+ " return B, out2, out3, out4\n"
466
+ "end\n"
467
+ )
468
+ assert source == expected
469
+
470
+
471
+ def test_jl_loops():
472
+ # Note: an Julia programmer would probably vectorize this across one or
473
+ # more dimensions. Also, size(A) would be used rather than passing in m
474
+ # and n. Perhaps users would expect us to vectorize automatically here?
475
+ # Or is it possible to represent such things using IndexedBase?
476
+ from sympy.tensor import IndexedBase, Idx
477
+ from sympy.core.symbol import symbols
478
+ n, m = symbols('n m', integer=True)
479
+ A = IndexedBase('A')
480
+ x = IndexedBase('x')
481
+ y = IndexedBase('y')
482
+ i = Idx('i', m)
483
+ j = Idx('j', n)
484
+ result, = codegen(('mat_vec_mult', Eq(y[i], A[i, j]*x[j])), "Julia",
485
+ header=False, empty=False)
486
+ source = result[1]
487
+ expected = (
488
+ 'function mat_vec_mult(y, A, m, n, x)\n'
489
+ ' for i = 1:m\n'
490
+ ' y[i] = 0\n'
491
+ ' end\n'
492
+ ' for i = 1:m\n'
493
+ ' for j = 1:n\n'
494
+ ' y[i] = %(rhs)s + y[i]\n'
495
+ ' end\n'
496
+ ' end\n'
497
+ ' return y\n'
498
+ 'end\n'
499
+ )
500
+ assert (source == expected % {'rhs': 'A[%s,%s] .* x[j]' % (i, j)} or
501
+ source == expected % {'rhs': 'x[j] .* A[%s,%s]' % (i, j)})
502
+
503
+
504
+ def test_jl_tensor_loops_multiple_contractions():
505
+ # see comments in previous test about vectorizing
506
+ from sympy.tensor import IndexedBase, Idx
507
+ from sympy.core.symbol import symbols
508
+ n, m, o, p = symbols('n m o p', integer=True)
509
+ A = IndexedBase('A')
510
+ B = IndexedBase('B')
511
+ y = IndexedBase('y')
512
+ i = Idx('i', m)
513
+ j = Idx('j', n)
514
+ k = Idx('k', o)
515
+ l = Idx('l', p)
516
+ result, = codegen(('tensorthing', Eq(y[i], B[j, k, l]*A[i, j, k, l])),
517
+ "Julia", header=False, empty=False)
518
+ source = result[1]
519
+ expected = (
520
+ 'function tensorthing(y, A, B, m, n, o, p)\n'
521
+ ' for i = 1:m\n'
522
+ ' y[i] = 0\n'
523
+ ' end\n'
524
+ ' for i = 1:m\n'
525
+ ' for j = 1:n\n'
526
+ ' for k = 1:o\n'
527
+ ' for l = 1:p\n'
528
+ ' y[i] = A[i,j,k,l] .* B[j,k,l] + y[i]\n'
529
+ ' end\n'
530
+ ' end\n'
531
+ ' end\n'
532
+ ' end\n'
533
+ ' return y\n'
534
+ 'end\n'
535
+ )
536
+ assert source == expected
537
+
538
+
539
+ def test_jl_InOutArgument():
540
+ expr = Equality(x, x**2)
541
+ name_expr = ("mysqr", expr)
542
+ result, = codegen(name_expr, "Julia", header=False, empty=False)
543
+ source = result[1]
544
+ expected = (
545
+ "function mysqr(x)\n"
546
+ " x = x .^ 2\n"
547
+ " return x\n"
548
+ "end\n"
549
+ )
550
+ assert source == expected
551
+
552
+
553
+ def test_jl_InOutArgument_order():
554
+ # can specify the order as (x, y)
555
+ expr = Equality(x, x**2 + y)
556
+ name_expr = ("test", expr)
557
+ result, = codegen(name_expr, "Julia", header=False,
558
+ empty=False, argument_sequence=(x,y))
559
+ source = result[1]
560
+ expected = (
561
+ "function test(x, y)\n"
562
+ " x = x .^ 2 + y\n"
563
+ " return x\n"
564
+ "end\n"
565
+ )
566
+ assert source == expected
567
+ # make sure it gives (x, y) not (y, x)
568
+ expr = Equality(x, x**2 + y)
569
+ name_expr = ("test", expr)
570
+ result, = codegen(name_expr, "Julia", header=False, empty=False)
571
+ source = result[1]
572
+ expected = (
573
+ "function test(x, y)\n"
574
+ " x = x .^ 2 + y\n"
575
+ " return x\n"
576
+ "end\n"
577
+ )
578
+ assert source == expected
579
+
580
+
581
+ def test_jl_not_supported():
582
+ f = Function('f')
583
+ name_expr = ("test", [f(x).diff(x), S.ComplexInfinity])
584
+ result, = codegen(name_expr, "Julia", header=False, empty=False)
585
+ source = result[1]
586
+ expected = (
587
+ "function test(x)\n"
588
+ " # unsupported: Derivative(f(x), x)\n"
589
+ " # unsupported: zoo\n"
590
+ " out1 = Derivative(f(x), x)\n"
591
+ " out2 = zoo\n"
592
+ " return out1, out2\n"
593
+ "end\n"
594
+ )
595
+ assert source == expected
596
+
597
+
598
+ def test_global_vars_octave():
599
+ x, y, z, t = symbols("x y z t")
600
+ result = codegen(('f', x*y), "Julia", header=False, empty=False,
601
+ global_vars=(y,))
602
+ source = result[0][1]
603
+ expected = (
604
+ "function f(x)\n"
605
+ " out1 = x .* y\n"
606
+ " return out1\n"
607
+ "end\n"
608
+ )
609
+ assert source == expected
610
+
611
+ result = codegen(('f', x*y+z), "Julia", header=False, empty=False,
612
+ argument_sequence=(x, y), global_vars=(z, t))
613
+ source = result[0][1]
614
+ expected = (
615
+ "function f(x, y)\n"
616
+ " out1 = x .* y + z\n"
617
+ " return out1\n"
618
+ "end\n"
619
+ )
620
+ assert source == expected
shared/package-files/41/418c1561a3f8b5203203ac455f5bd0f9f450e1f7cfc32ebce2a3dfa57ae33d0d/orthogonal.cpython-311.pyc ADDED
Binary file (25.7 kB). View file
 
shared/package-files/41/4193c4708f649ac3613873f70ffdfd9e9a5ad3c53d9afdda1d0b8e4d2f8e43ce/upsample_linear1d_meta.h ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeMetaFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/TensorIterator.h>
13
+ #include <ATen/TensorMeta.h>
14
+ #include <tuple>
15
+ #include <vector>
16
+
17
+ namespace at {
18
+ namespace meta {
19
+
20
+ struct TORCH_API structured_upsample_linear1d : public at::impl::MetaBase {
21
+
22
+
23
+ void meta(const at::Tensor & self, at::ArrayRef<int64_t> output_size, bool align_corners, ::std::optional<double> scales);
24
+ };
25
+
26
+ } // namespace native
27
+ } // namespace at
shared/package-files/41/419441196543bf6adff43168a0bdf1a8c1238973d92e28826d9b52b56569b47d/native_layer_norm_compositeexplicitautograd_dispatch.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor> native_layer_norm(const at::Tensor & input, at::IntArrayRef normalized_shape, const ::std::optional<at::Tensor> & weight, const ::std::optional<at::Tensor> & bias, double eps);
21
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor> native_layer_norm_symint(const at::Tensor & input, c10::SymIntArrayRef normalized_shape, const ::std::optional<at::Tensor> & weight, const ::std::optional<at::Tensor> & bias, double eps);
22
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> native_layer_norm_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & input, at::IntArrayRef normalized_shape, const ::std::optional<at::Tensor> & weight, const ::std::optional<at::Tensor> & bias, double eps);
23
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> native_layer_norm_outf(const at::Tensor & input, at::IntArrayRef normalized_shape, const ::std::optional<at::Tensor> & weight, const ::std::optional<at::Tensor> & bias, double eps, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2);
24
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> native_layer_norm_symint_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & input, c10::SymIntArrayRef normalized_shape, const ::std::optional<at::Tensor> & weight, const ::std::optional<at::Tensor> & bias, double eps);
25
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> native_layer_norm_symint_outf(const at::Tensor & input, c10::SymIntArrayRef normalized_shape, const ::std::optional<at::Tensor> & weight, const ::std::optional<at::Tensor> & bias, double eps, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2);
26
+
27
+ } // namespace compositeexplicitautograd
28
+ } // namespace at
shared/package-files/41/41952fafbed3c491e37604153698a102ea20960d608551ce4c314e55727da5c1/test_ipython.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests of tools for setting up interactive IPython sessions. """
2
+
3
+ from sympy.interactive.session import (init_ipython_session,
4
+ enable_automatic_symbols, enable_automatic_int_sympification)
5
+
6
+ from sympy.core import Symbol, Rational, Integer
7
+ from sympy.external import import_module
8
+ from sympy.testing.pytest import raises
9
+
10
+ # TODO: The code below could be made more granular with something like:
11
+ #
12
+ # @requires('IPython', version=">=1.0")
13
+ # def test_automatic_symbols(ipython):
14
+
15
+ ipython = import_module("IPython", min_module_version="1.0")
16
+
17
+ if not ipython:
18
+ #bin/test will not execute any tests now
19
+ disabled = True
20
+
21
+ # WARNING: These tests will modify the existing IPython environment. IPython
22
+ # uses a single instance for its interpreter, so there is no way to isolate
23
+ # the test from another IPython session. It also means that if this test is
24
+ # run twice in the same Python session it will fail. This isn't usually a
25
+ # problem because the test suite is run in a subprocess by default, but if the
26
+ # tests are run with subprocess=False it can pollute the current IPython
27
+ # session. See the discussion in issue #15149.
28
+
29
+ def test_automatic_symbols():
30
+ # NOTE: Because of the way the hook works, you have to use run_cell(code,
31
+ # True). This means that the code must have no Out, or it will be printed
32
+ # during the tests.
33
+ app = init_ipython_session()
34
+ app.run_cell("from sympy import *")
35
+
36
+ enable_automatic_symbols(app)
37
+
38
+ symbol = "verylongsymbolname"
39
+ assert symbol not in app.user_ns
40
+ app.run_cell("a = %s" % symbol, True)
41
+ assert symbol not in app.user_ns
42
+ app.run_cell("a = type(%s)" % symbol, True)
43
+ assert app.user_ns['a'] == Symbol
44
+ app.run_cell("%s = Symbol('%s')" % (symbol, symbol), True)
45
+ assert symbol in app.user_ns
46
+
47
+ # Check that built-in names aren't overridden
48
+ app.run_cell("a = all == __builtin__.all", True)
49
+ assert "all" not in app.user_ns
50
+ assert app.user_ns['a'] is True
51
+
52
+ # Check that SymPy names aren't overridden
53
+ app.run_cell("import sympy")
54
+ app.run_cell("a = factorial == sympy.factorial", True)
55
+ assert app.user_ns['a'] is True
56
+
57
+
58
+ def test_int_to_Integer():
59
+ # XXX: Warning, don't test with == here. 0.5 == Rational(1, 2) is True!
60
+ app = init_ipython_session()
61
+ app.run_cell("from sympy import Integer")
62
+ app.run_cell("a = 1")
63
+ assert isinstance(app.user_ns['a'], int)
64
+
65
+ enable_automatic_int_sympification(app)
66
+ app.run_cell("a = 1/2")
67
+ assert isinstance(app.user_ns['a'], Rational)
68
+ app.run_cell("a = 1")
69
+ assert isinstance(app.user_ns['a'], Integer)
70
+ app.run_cell("a = int(1)")
71
+ assert isinstance(app.user_ns['a'], int)
72
+ app.run_cell("a = (1/\n2)")
73
+ assert app.user_ns['a'] == Rational(1, 2)
74
+ # TODO: How can we test that the output of a SyntaxError is the original
75
+ # input, not the transformed input?
76
+
77
+
78
+ def test_ipythonprinting():
79
+ # Initialize and setup IPython session
80
+ app = init_ipython_session()
81
+ app.run_cell("ip = get_ipython()")
82
+ app.run_cell("inst = ip.instance()")
83
+ app.run_cell("format = inst.display_formatter.format")
84
+ app.run_cell("from sympy import Symbol")
85
+
86
+ # Printing without printing extension
87
+ app.run_cell("a = format(Symbol('pi'))")
88
+ app.run_cell("a2 = format(Symbol('pi')**2)")
89
+ # Deal with API change starting at IPython 1.0
90
+ if int(ipython.__version__.split(".")[0]) < 1:
91
+ assert app.user_ns['a']['text/plain'] == "pi"
92
+ assert app.user_ns['a2']['text/plain'] == "pi**2"
93
+ else:
94
+ assert app.user_ns['a'][0]['text/plain'] == "pi"
95
+ assert app.user_ns['a2'][0]['text/plain'] == "pi**2"
96
+
97
+ # Load printing extension
98
+ app.run_cell("from sympy import init_printing")
99
+ app.run_cell("init_printing()")
100
+ # Printing with printing extension
101
+ app.run_cell("a = format(Symbol('pi'))")
102
+ app.run_cell("a2 = format(Symbol('pi')**2)")
103
+ # Deal with API change starting at IPython 1.0
104
+ if int(ipython.__version__.split(".")[0]) < 1:
105
+ assert app.user_ns['a']['text/plain'] in ('\N{GREEK SMALL LETTER PI}', 'pi')
106
+ assert app.user_ns['a2']['text/plain'] in (' 2\n\N{GREEK SMALL LETTER PI} ', ' 2\npi ')
107
+ else:
108
+ assert app.user_ns['a'][0]['text/plain'] in ('\N{GREEK SMALL LETTER PI}', 'pi')
109
+ assert app.user_ns['a2'][0]['text/plain'] in (' 2\n\N{GREEK SMALL LETTER PI} ', ' 2\npi ')
110
+
111
+
112
+ def test_print_builtin_option():
113
+ # Initialize and setup IPython session
114
+ app = init_ipython_session()
115
+ app.run_cell("ip = get_ipython()")
116
+ app.run_cell("inst = ip.instance()")
117
+ app.run_cell("format = inst.display_formatter.format")
118
+ app.run_cell("from sympy import Symbol")
119
+ app.run_cell("from sympy import init_printing")
120
+
121
+ app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
122
+ # Deal with API change starting at IPython 1.0
123
+ if int(ipython.__version__.split(".")[0]) < 1:
124
+ text = app.user_ns['a']['text/plain']
125
+ raises(KeyError, lambda: app.user_ns['a']['text/latex'])
126
+ else:
127
+ text = app.user_ns['a'][0]['text/plain']
128
+ raises(KeyError, lambda: app.user_ns['a'][0]['text/latex'])
129
+ # XXX: How can we make this ignore the terminal width? This test fails if
130
+ # the terminal is too narrow.
131
+ assert text in ("{pi: 3.14, n_i: 3}",
132
+ '{n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3, \N{GREEK SMALL LETTER PI}: 3.14}',
133
+ "{n_i: 3, pi: 3.14}",
134
+ '{\N{GREEK SMALL LETTER PI}: 3.14, n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3}')
135
+
136
+ # If we enable the default printing, then the dictionary's should render
137
+ # as a LaTeX version of the whole dict: ${\pi: 3.14, n_i: 3}$
138
+ app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
139
+ app.run_cell("init_printing(use_latex=True)")
140
+ app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
141
+ # Deal with API change starting at IPython 1.0
142
+ if int(ipython.__version__.split(".")[0]) < 1:
143
+ text = app.user_ns['a']['text/plain']
144
+ latex = app.user_ns['a']['text/latex']
145
+ else:
146
+ text = app.user_ns['a'][0]['text/plain']
147
+ latex = app.user_ns['a'][0]['text/latex']
148
+ assert text in ("{pi: 3.14, n_i: 3}",
149
+ '{n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3, \N{GREEK SMALL LETTER PI}: 3.14}',
150
+ "{n_i: 3, pi: 3.14}",
151
+ '{\N{GREEK SMALL LETTER PI}: 3.14, n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3}')
152
+ assert latex == r'$\displaystyle \left\{ n_{i} : 3, \ \pi : 3.14\right\}$'
153
+
154
+ # Objects with an _latex overload should also be handled by our tuple
155
+ # printer.
156
+ app.run_cell("""\
157
+ class WithOverload:
158
+ def _latex(self, printer):
159
+ return r"\\LaTeX"
160
+ """)
161
+ app.run_cell("a = format((WithOverload(),))")
162
+ # Deal with API change starting at IPython 1.0
163
+ if int(ipython.__version__.split(".")[0]) < 1:
164
+ latex = app.user_ns['a']['text/latex']
165
+ else:
166
+ latex = app.user_ns['a'][0]['text/latex']
167
+ assert latex == r'$\displaystyle \left( \LaTeX,\right)$'
168
+
169
+ app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
170
+ app.run_cell("init_printing(use_latex=True, print_builtin=False)")
171
+ app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
172
+ # Deal with API change starting at IPython 1.0
173
+ if int(ipython.__version__.split(".")[0]) < 1:
174
+ text = app.user_ns['a']['text/plain']
175
+ raises(KeyError, lambda: app.user_ns['a']['text/latex'])
176
+ else:
177
+ text = app.user_ns['a'][0]['text/plain']
178
+ raises(KeyError, lambda: app.user_ns['a'][0]['text/latex'])
179
+ # Note : In Python 3 we have one text type: str which holds Unicode data
180
+ # and two byte types bytes and bytearray.
181
+ # Python 3.3.3 + IPython 0.13.2 gives: '{n_i: 3, pi: 3.14}'
182
+ # Python 3.3.3 + IPython 1.1.0 gives: '{n_i: 3, pi: 3.14}'
183
+ assert text in ("{pi: 3.14, n_i: 3}", "{n_i: 3, pi: 3.14}")
184
+
185
+
186
+ def test_builtin_containers():
187
+ # Initialize and setup IPython session
188
+ app = init_ipython_session()
189
+ app.run_cell("ip = get_ipython()")
190
+ app.run_cell("inst = ip.instance()")
191
+ app.run_cell("format = inst.display_formatter.format")
192
+ app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
193
+ app.run_cell("from sympy import init_printing, Matrix")
194
+ app.run_cell('init_printing(use_latex=True, use_unicode=False)')
195
+
196
+ # Make sure containers that shouldn't pretty print don't.
197
+ app.run_cell('a = format((True, False))')
198
+ app.run_cell('import sys')
199
+ app.run_cell('b = format(sys.flags)')
200
+ app.run_cell('c = format((Matrix([1, 2]),))')
201
+ # Deal with API change starting at IPython 1.0
202
+ if int(ipython.__version__.split(".")[0]) < 1:
203
+ assert app.user_ns['a']['text/plain'] == '(True, False)'
204
+ assert 'text/latex' not in app.user_ns['a']
205
+ assert app.user_ns['b']['text/plain'][:10] == 'sys.flags('
206
+ assert 'text/latex' not in app.user_ns['b']
207
+ assert app.user_ns['c']['text/plain'] == \
208
+ """\
209
+ [1] \n\
210
+ ([ ],)
211
+ [2] \
212
+ """
213
+ assert app.user_ns['c']['text/latex'] == '$\\displaystyle \\left( \\left[\\begin{matrix}1\\\\2\\end{matrix}\\right],\\right)$'
214
+ else:
215
+ assert app.user_ns['a'][0]['text/plain'] == '(True, False)'
216
+ assert 'text/latex' not in app.user_ns['a'][0]
217
+ assert app.user_ns['b'][0]['text/plain'][:10] == 'sys.flags('
218
+ assert 'text/latex' not in app.user_ns['b'][0]
219
+ assert app.user_ns['c'][0]['text/plain'] == \
220
+ """\
221
+ [1] \n\
222
+ ([ ],)
223
+ [2] \
224
+ """
225
+ assert app.user_ns['c'][0]['text/latex'] == '$\\displaystyle \\left( \\left[\\begin{matrix}1\\\\2\\end{matrix}\\right],\\right)$'
226
+
227
+ def test_matplotlib_bad_latex():
228
+ # Initialize and setup IPython session
229
+ app = init_ipython_session()
230
+ app.run_cell("import IPython")
231
+ app.run_cell("ip = get_ipython()")
232
+ app.run_cell("inst = ip.instance()")
233
+ app.run_cell("format = inst.display_formatter.format")
234
+ app.run_cell("from sympy import init_printing, Matrix")
235
+ app.run_cell("init_printing(use_latex='matplotlib')")
236
+
237
+ # The png formatter is not enabled by default in this context
238
+ app.run_cell("inst.display_formatter.formatters['image/png'].enabled = True")
239
+
240
+ # Make sure no warnings are raised by IPython
241
+ app.run_cell("import warnings")
242
+ # IPython.core.formatters.FormatterWarning was introduced in IPython 2.0
243
+ if int(ipython.__version__.split(".")[0]) < 2:
244
+ app.run_cell("warnings.simplefilter('error')")
245
+ else:
246
+ app.run_cell("warnings.simplefilter('error', IPython.core.formatters.FormatterWarning)")
247
+
248
+ # This should not raise an exception
249
+ app.run_cell("a = format(Matrix([1, 2, 3]))")
250
+
251
+ # issue 9799
252
+ app.run_cell("from sympy import Piecewise, Symbol, Eq")
253
+ app.run_cell("x = Symbol('x'); pw = format(Piecewise((1, Eq(x, 0)), (0, True)))")
254
+
255
+
256
+ def test_override_repr_latex():
257
+ # Initialize and setup IPython session
258
+ app = init_ipython_session()
259
+ app.run_cell("import IPython")
260
+ app.run_cell("ip = get_ipython()")
261
+ app.run_cell("inst = ip.instance()")
262
+ app.run_cell("format = inst.display_formatter.format")
263
+ app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
264
+ app.run_cell("from sympy import init_printing")
265
+ app.run_cell("from sympy import Symbol")
266
+ app.run_cell("init_printing(use_latex=True)")
267
+ app.run_cell("""\
268
+ class SymbolWithOverload(Symbol):
269
+ def _repr_latex_(self):
270
+ return r"Hello " + super()._repr_latex_() + " world"
271
+ """)
272
+ app.run_cell("a = format(SymbolWithOverload('s'))")
273
+
274
+ if int(ipython.__version__.split(".")[0]) < 1:
275
+ latex = app.user_ns['a']['text/latex']
276
+ else:
277
+ latex = app.user_ns['a'][0]['text/latex']
278
+ assert latex == r'Hello $\displaystyle s$ world'
shared/package-files/41/4195e10347eb055351b006ab1033998a32305786428348d4dbf88696e71c1f38/test_common.cpython-311.pyc ADDED
Binary file (6.51 kB). View file
 
shared/package-files/41/419611038ad585a4dc27bd75d052763344c82ad45da3cf35c35284c4dd0b0a78/windows_events.py ADDED
@@ -0,0 +1,952 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Selector and proactor event loops for Windows."""
2
+
3
+ import sys
4
+
5
+ if sys.platform != 'win32': # pragma: no cover
6
+ raise ImportError('win32 only')
7
+
8
+ import _overlapped
9
+ import _winapi
10
+ import errno
11
+ import math
12
+ import msvcrt
13
+ import socket
14
+ import struct
15
+ import time
16
+ import weakref
17
+
18
+ from . import events
19
+ from . import base_subprocess
20
+ from . import futures
21
+ from . import exceptions
22
+ from . import proactor_events
23
+ from . import selector_events
24
+ from . import tasks
25
+ from . import windows_utils
26
+ from .log import logger
27
+
28
+
29
+ __all__ = (
30
+ 'SelectorEventLoop', 'ProactorEventLoop', 'IocpProactor',
31
+ 'DefaultEventLoopPolicy', 'WindowsSelectorEventLoopPolicy',
32
+ 'WindowsProactorEventLoopPolicy',
33
+ )
34
+
35
+
36
+ NULL = _winapi.NULL
37
+ INFINITE = _winapi.INFINITE
38
+ ERROR_CONNECTION_REFUSED = 1225
39
+ ERROR_CONNECTION_ABORTED = 1236
40
+
41
+ # Initial delay in seconds for connect_pipe() before retrying to connect
42
+ CONNECT_PIPE_INIT_DELAY = 0.001
43
+
44
+ # Maximum delay in seconds for connect_pipe() before retrying to connect
45
+ CONNECT_PIPE_MAX_DELAY = 0.100
46
+
47
+
48
+ class _OverlappedFuture(futures.Future):
49
+ """Subclass of Future which represents an overlapped operation.
50
+
51
+ Cancelling it will immediately cancel the overlapped operation.
52
+ """
53
+
54
+ def __init__(self, ov, *, loop=None):
55
+ super().__init__(loop=loop)
56
+ if self._source_traceback:
57
+ del self._source_traceback[-1]
58
+ self._ov = ov
59
+
60
+ def _repr_info(self):
61
+ info = super()._repr_info()
62
+ if self._ov is not None:
63
+ state = 'pending' if self._ov.pending else 'completed'
64
+ info.insert(1, f'overlapped=<{state}, {self._ov.address:#x}>')
65
+ return info
66
+
67
+ def _cancel_overlapped(self):
68
+ if self._ov is None:
69
+ return
70
+ try:
71
+ self._ov.cancel()
72
+ except OSError as exc:
73
+ context = {
74
+ 'message': 'Cancelling an overlapped future failed',
75
+ 'exception': exc,
76
+ 'future': self,
77
+ }
78
+ if self._source_traceback:
79
+ context['source_traceback'] = self._source_traceback
80
+ self._loop.call_exception_handler(context)
81
+ self._ov = None
82
+
83
+ def cancel(self, msg=None):
84
+ self._cancel_overlapped()
85
+ return super().cancel(msg=msg)
86
+
87
+ def set_exception(self, exception):
88
+ super().set_exception(exception)
89
+ self._cancel_overlapped()
90
+
91
+ def set_result(self, result):
92
+ super().set_result(result)
93
+ self._ov = None
94
+
95
+
96
+ class _BaseWaitHandleFuture(futures.Future):
97
+ """Subclass of Future which represents a wait handle."""
98
+
99
+ def __init__(self, ov, handle, wait_handle, *, loop=None):
100
+ super().__init__(loop=loop)
101
+ if self._source_traceback:
102
+ del self._source_traceback[-1]
103
+ # Keep a reference to the Overlapped object to keep it alive until the
104
+ # wait is unregistered
105
+ self._ov = ov
106
+ self._handle = handle
107
+ self._wait_handle = wait_handle
108
+
109
+ # Should we call UnregisterWaitEx() if the wait completes
110
+ # or is cancelled?
111
+ self._registered = True
112
+
113
+ def _poll(self):
114
+ # non-blocking wait: use a timeout of 0 millisecond
115
+ return (_winapi.WaitForSingleObject(self._handle, 0) ==
116
+ _winapi.WAIT_OBJECT_0)
117
+
118
+ def _repr_info(self):
119
+ info = super()._repr_info()
120
+ info.append(f'handle={self._handle:#x}')
121
+ if self._handle is not None:
122
+ state = 'signaled' if self._poll() else 'waiting'
123
+ info.append(state)
124
+ if self._wait_handle is not None:
125
+ info.append(f'wait_handle={self._wait_handle:#x}')
126
+ return info
127
+
128
+ def _unregister_wait_cb(self, fut):
129
+ # The wait was unregistered: it's not safe to destroy the Overlapped
130
+ # object
131
+ self._ov = None
132
+
133
+ def _unregister_wait(self):
134
+ if not self._registered:
135
+ return
136
+ self._registered = False
137
+
138
+ wait_handle = self._wait_handle
139
+ self._wait_handle = None
140
+ try:
141
+ _overlapped.UnregisterWait(wait_handle)
142
+ except OSError as exc:
143
+ if exc.winerror != _overlapped.ERROR_IO_PENDING:
144
+ context = {
145
+ 'message': 'Failed to unregister the wait handle',
146
+ 'exception': exc,
147
+ 'future': self,
148
+ }
149
+ if self._source_traceback:
150
+ context['source_traceback'] = self._source_traceback
151
+ self._loop.call_exception_handler(context)
152
+ return
153
+ # ERROR_IO_PENDING means that the unregister is pending
154
+
155
+ self._unregister_wait_cb(None)
156
+
157
+ def cancel(self, msg=None):
158
+ self._unregister_wait()
159
+ return super().cancel(msg=msg)
160
+
161
+ def set_exception(self, exception):
162
+ self._unregister_wait()
163
+ super().set_exception(exception)
164
+
165
+ def set_result(self, result):
166
+ self._unregister_wait()
167
+ super().set_result(result)
168
+
169
+
170
+ class _WaitCancelFuture(_BaseWaitHandleFuture):
171
+ """Subclass of Future which represents a wait for the cancellation of a
172
+ _WaitHandleFuture using an event.
173
+ """
174
+
175
+ def __init__(self, ov, event, wait_handle, *, loop=None):
176
+ super().__init__(ov, event, wait_handle, loop=loop)
177
+
178
+ self._done_callback = None
179
+
180
+ def cancel(self):
181
+ raise RuntimeError("_WaitCancelFuture must not be cancelled")
182
+
183
+ def set_result(self, result):
184
+ super().set_result(result)
185
+ if self._done_callback is not None:
186
+ self._done_callback(self)
187
+
188
+ def set_exception(self, exception):
189
+ super().set_exception(exception)
190
+ if self._done_callback is not None:
191
+ self._done_callback(self)
192
+
193
+
194
+ class _WaitHandleFuture(_BaseWaitHandleFuture):
195
+ def __init__(self, ov, handle, wait_handle, proactor, *, loop=None):
196
+ super().__init__(ov, handle, wait_handle, loop=loop)
197
+ self._proactor = proactor
198
+ self._unregister_proactor = True
199
+ self._event = _overlapped.CreateEvent(None, True, False, None)
200
+ self._event_fut = None
201
+
202
+ def _unregister_wait_cb(self, fut):
203
+ if self._event is not None:
204
+ _winapi.CloseHandle(self._event)
205
+ self._event = None
206
+ self._event_fut = None
207
+
208
+ # If the wait was cancelled, the wait may never be signalled, so
209
+ # it's required to unregister it. Otherwise, IocpProactor.close() will
210
+ # wait forever for an event which will never come.
211
+ #
212
+ # If the IocpProactor already received the event, it's safe to call
213
+ # _unregister() because we kept a reference to the Overlapped object
214
+ # which is used as a unique key.
215
+ self._proactor._unregister(self._ov)
216
+ self._proactor = None
217
+
218
+ super()._unregister_wait_cb(fut)
219
+
220
+ def _unregister_wait(self):
221
+ if not self._registered:
222
+ return
223
+ self._registered = False
224
+
225
+ wait_handle = self._wait_handle
226
+ self._wait_handle = None
227
+ try:
228
+ _overlapped.UnregisterWaitEx(wait_handle, self._event)
229
+ except OSError as exc:
230
+ if exc.winerror != _overlapped.ERROR_IO_PENDING:
231
+ context = {
232
+ 'message': 'Failed to unregister the wait handle',
233
+ 'exception': exc,
234
+ 'future': self,
235
+ }
236
+ if self._source_traceback:
237
+ context['source_traceback'] = self._source_traceback
238
+ self._loop.call_exception_handler(context)
239
+ return
240
+ # ERROR_IO_PENDING is not an error, the wait was unregistered
241
+
242
+ self._event_fut = self._proactor._wait_cancel(self._event,
243
+ self._unregister_wait_cb)
244
+
245
+
246
+ class PipeServer(object):
247
+ """Class representing a pipe server.
248
+
249
+ This is much like a bound, listening socket.
250
+ """
251
+ def __init__(self, address):
252
+ self._address = address
253
+ self._free_instances = weakref.WeakSet()
254
+ # initialize the pipe attribute before calling _server_pipe_handle()
255
+ # because this function can raise an exception and the destructor calls
256
+ # the close() method
257
+ self._pipe = None
258
+ self._accept_pipe_future = None
259
+ self._pipe = self._server_pipe_handle(True)
260
+
261
+ def _get_unconnected_pipe(self):
262
+ # Create new instance and return previous one. This ensures
263
+ # that (until the server is closed) there is always at least
264
+ # one pipe handle for address. Therefore if a client attempt
265
+ # to connect it will not fail with FileNotFoundError.
266
+ tmp, self._pipe = self._pipe, self._server_pipe_handle(False)
267
+ return tmp
268
+
269
+ def _server_pipe_handle(self, first):
270
+ # Return a wrapper for a new pipe handle.
271
+ if self.closed():
272
+ return None
273
+ flags = _winapi.PIPE_ACCESS_DUPLEX | _winapi.FILE_FLAG_OVERLAPPED
274
+ if first:
275
+ flags |= _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE
276
+ h = _winapi.CreateNamedPipe(
277
+ self._address, flags,
278
+ _winapi.PIPE_TYPE_MESSAGE | _winapi.PIPE_READMODE_MESSAGE |
279
+ _winapi.PIPE_WAIT,
280
+ _winapi.PIPE_UNLIMITED_INSTANCES,
281
+ windows_utils.BUFSIZE, windows_utils.BUFSIZE,
282
+ _winapi.NMPWAIT_WAIT_FOREVER, _winapi.NULL)
283
+ pipe = windows_utils.PipeHandle(h)
284
+ self._free_instances.add(pipe)
285
+ return pipe
286
+
287
+ def closed(self):
288
+ return (self._address is None)
289
+
290
+ def close(self):
291
+ if self._accept_pipe_future is not None:
292
+ self._accept_pipe_future.cancel()
293
+ self._accept_pipe_future = None
294
+ # Close all instances which have not been connected to by a client.
295
+ if self._address is not None:
296
+ for pipe in self._free_instances:
297
+ pipe.close()
298
+ self._pipe = None
299
+ self._address = None
300
+ self._free_instances.clear()
301
+
302
+ __del__ = close
303
+
304
+
305
+ class _WindowsSelectorEventLoop(selector_events.BaseSelectorEventLoop):
306
+ """Windows version of selector event loop."""
307
+
308
+
309
+ class ProactorEventLoop(proactor_events.BaseProactorEventLoop):
310
+ """Windows version of proactor event loop using IOCP."""
311
+
312
+ def __init__(self, proactor=None):
313
+ if proactor is None:
314
+ proactor = IocpProactor()
315
+ super().__init__(proactor)
316
+
317
+ def run_forever(self):
318
+ try:
319
+ assert self._self_reading_future is None
320
+ self.call_soon(self._loop_self_reading)
321
+ super().run_forever()
322
+ finally:
323
+ if self._self_reading_future is not None:
324
+ ov = self._self_reading_future._ov
325
+ self._self_reading_future.cancel()
326
+ # self_reading_future always uses IOCP, so even though it's
327
+ # been cancelled, we need to make sure that the IOCP message
328
+ # is received so that the kernel is not holding on to the
329
+ # memory, possibly causing memory corruption later. Only
330
+ # unregister it if IO is complete in all respects. Otherwise
331
+ # we need another _poll() later to complete the IO.
332
+ if ov is not None and not ov.pending:
333
+ self._proactor._unregister(ov)
334
+ self._self_reading_future = None
335
+
336
+ async def create_pipe_connection(self, protocol_factory, address):
337
+ f = self._proactor.connect_pipe(address)
338
+ pipe = await f
339
+ protocol = protocol_factory()
340
+ trans = self._make_duplex_pipe_transport(pipe, protocol,
341
+ extra={'addr': address})
342
+ return trans, protocol
343
+
344
+ async def start_serving_pipe(self, protocol_factory, address):
345
+ server = PipeServer(address)
346
+
347
+ def loop_accept_pipe(f=None):
348
+ pipe = None
349
+ try:
350
+ if f:
351
+ pipe = f.result()
352
+ server._free_instances.discard(pipe)
353
+
354
+ if server.closed():
355
+ # A client connected before the server was closed:
356
+ # drop the client (close the pipe) and exit
357
+ pipe.close()
358
+ return
359
+
360
+ protocol = protocol_factory()
361
+ self._make_duplex_pipe_transport(
362
+ pipe, protocol, extra={'addr': address})
363
+
364
+ pipe = server._get_unconnected_pipe()
365
+ if pipe is None:
366
+ return
367
+
368
+ f = self._proactor.accept_pipe(pipe)
369
+ except BrokenPipeError:
370
+ if pipe and pipe.fileno() != -1:
371
+ pipe.close()
372
+ self.call_soon(loop_accept_pipe)
373
+ except OSError as exc:
374
+ if pipe and pipe.fileno() != -1:
375
+ self.call_exception_handler({
376
+ 'message': 'Pipe accept failed',
377
+ 'exception': exc,
378
+ 'pipe': pipe,
379
+ })
380
+ pipe.close()
381
+ elif self._debug:
382
+ logger.warning("Accept pipe failed on pipe %r",
383
+ pipe, exc_info=True)
384
+ self.call_soon(loop_accept_pipe)
385
+ except exceptions.CancelledError:
386
+ if pipe:
387
+ pipe.close()
388
+ else:
389
+ server._accept_pipe_future = f
390
+ f.add_done_callback(loop_accept_pipe)
391
+
392
+ self.call_soon(loop_accept_pipe)
393
+ return [server]
394
+
395
+ async def _make_subprocess_transport(self, protocol, args, shell,
396
+ stdin, stdout, stderr, bufsize,
397
+ extra=None, **kwargs):
398
+ waiter = self.create_future()
399
+ transp = _WindowsSubprocessTransport(self, protocol, args, shell,
400
+ stdin, stdout, stderr, bufsize,
401
+ waiter=waiter, extra=extra,
402
+ **kwargs)
403
+ try:
404
+ await waiter
405
+ except (SystemExit, KeyboardInterrupt):
406
+ raise
407
+ except BaseException:
408
+ transp.close()
409
+ await transp._wait()
410
+ raise
411
+
412
+ return transp
413
+
414
+
415
+ class IocpProactor:
416
+ """Proactor implementation using IOCP."""
417
+
418
+ def __init__(self, concurrency=INFINITE):
419
+ self._loop = None
420
+ self._results = []
421
+ self._iocp = _overlapped.CreateIoCompletionPort(
422
+ _overlapped.INVALID_HANDLE_VALUE, NULL, 0, concurrency)
423
+ self._cache = {}
424
+ self._registered = weakref.WeakSet()
425
+ self._unregistered = []
426
+ self._stopped_serving = weakref.WeakSet()
427
+
428
+ def _check_closed(self):
429
+ if self._iocp is None:
430
+ raise RuntimeError('IocpProactor is closed')
431
+
432
+ def __repr__(self):
433
+ info = ['overlapped#=%s' % len(self._cache),
434
+ 'result#=%s' % len(self._results)]
435
+ if self._iocp is None:
436
+ info.append('closed')
437
+ return '<%s %s>' % (self.__class__.__name__, " ".join(info))
438
+
439
+ def set_loop(self, loop):
440
+ self._loop = loop
441
+
442
+ def select(self, timeout=None):
443
+ if not self._results:
444
+ self._poll(timeout)
445
+ tmp = self._results
446
+ self._results = []
447
+ try:
448
+ return tmp
449
+ finally:
450
+ # Needed to break cycles when an exception occurs.
451
+ tmp = None
452
+
453
+ def _result(self, value):
454
+ fut = self._loop.create_future()
455
+ fut.set_result(value)
456
+ return fut
457
+
458
+ def recv(self, conn, nbytes, flags=0):
459
+ self._register_with_iocp(conn)
460
+ ov = _overlapped.Overlapped(NULL)
461
+ try:
462
+ if isinstance(conn, socket.socket):
463
+ ov.WSARecv(conn.fileno(), nbytes, flags)
464
+ else:
465
+ ov.ReadFile(conn.fileno(), nbytes)
466
+ except BrokenPipeError:
467
+ return self._result(b'')
468
+
469
+ def finish_recv(trans, key, ov):
470
+ try:
471
+ return ov.getresult()
472
+ except OSError as exc:
473
+ if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
474
+ _overlapped.ERROR_OPERATION_ABORTED):
475
+ raise ConnectionResetError(*exc.args)
476
+ else:
477
+ raise
478
+
479
+ return self._register(ov, conn, finish_recv)
480
+
481
+ def recv_into(self, conn, buf, flags=0):
482
+ self._register_with_iocp(conn)
483
+ ov = _overlapped.Overlapped(NULL)
484
+ try:
485
+ if isinstance(conn, socket.socket):
486
+ ov.WSARecvInto(conn.fileno(), buf, flags)
487
+ else:
488
+ ov.ReadFileInto(conn.fileno(), buf)
489
+ except BrokenPipeError:
490
+ return self._result(0)
491
+
492
+ def finish_recv(trans, key, ov):
493
+ try:
494
+ return ov.getresult()
495
+ except OSError as exc:
496
+ if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
497
+ _overlapped.ERROR_OPERATION_ABORTED):
498
+ raise ConnectionResetError(*exc.args)
499
+ else:
500
+ raise
501
+
502
+ return self._register(ov, conn, finish_recv)
503
+
504
+ def recvfrom(self, conn, nbytes, flags=0):
505
+ self._register_with_iocp(conn)
506
+ ov = _overlapped.Overlapped(NULL)
507
+ try:
508
+ ov.WSARecvFrom(conn.fileno(), nbytes, flags)
509
+ except BrokenPipeError:
510
+ return self._result((b'', None))
511
+
512
+ def finish_recv(trans, key, ov):
513
+ try:
514
+ return ov.getresult()
515
+ except OSError as exc:
516
+ # WSARecvFrom will report ERROR_PORT_UNREACHABLE when the same
517
+ # socket is used to send to an address that is not listening.
518
+ if exc.winerror == _overlapped.ERROR_PORT_UNREACHABLE:
519
+ return b'', None
520
+ if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
521
+ _overlapped.ERROR_OPERATION_ABORTED):
522
+ raise ConnectionResetError(*exc.args)
523
+ else:
524
+ raise
525
+
526
+ return self._register(ov, conn, finish_recv)
527
+
528
+ def recvfrom_into(self, conn, buf, flags=0):
529
+ self._register_with_iocp(conn)
530
+ ov = _overlapped.Overlapped(NULL)
531
+ try:
532
+ ov.WSARecvFromInto(conn.fileno(), buf, flags)
533
+ except BrokenPipeError:
534
+ return self._result((0, None))
535
+
536
+ def finish_recv(trans, key, ov):
537
+ try:
538
+ return ov.getresult()
539
+ except OSError as exc:
540
+ # WSARecvFrom will report ERROR_PORT_UNREACHABLE when the same
541
+ # socket is used to send to an address that is not listening.
542
+ if exc.winerror == _overlapped.ERROR_PORT_UNREACHABLE:
543
+ return 0, None
544
+ if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
545
+ _overlapped.ERROR_OPERATION_ABORTED):
546
+ raise ConnectionResetError(*exc.args)
547
+ else:
548
+ raise
549
+
550
+ return self._register(ov, conn, finish_recv)
551
+
552
+ def sendto(self, conn, buf, flags=0, addr=None):
553
+ self._register_with_iocp(conn)
554
+ ov = _overlapped.Overlapped(NULL)
555
+
556
+ ov.WSASendTo(conn.fileno(), buf, flags, addr)
557
+
558
+ def finish_send(trans, key, ov):
559
+ try:
560
+ return ov.getresult()
561
+ except OSError as exc:
562
+ if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
563
+ _overlapped.ERROR_OPERATION_ABORTED):
564
+ raise ConnectionResetError(*exc.args)
565
+ else:
566
+ raise
567
+
568
+ return self._register(ov, conn, finish_send)
569
+
570
+ def send(self, conn, buf, flags=0):
571
+ self._register_with_iocp(conn)
572
+ ov = _overlapped.Overlapped(NULL)
573
+ if isinstance(conn, socket.socket):
574
+ ov.WSASend(conn.fileno(), buf, flags)
575
+ else:
576
+ ov.WriteFile(conn.fileno(), buf)
577
+
578
+ def finish_send(trans, key, ov):
579
+ try:
580
+ return ov.getresult()
581
+ except OSError as exc:
582
+ if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
583
+ _overlapped.ERROR_OPERATION_ABORTED):
584
+ raise ConnectionResetError(*exc.args)
585
+ else:
586
+ raise
587
+
588
+ return self._register(ov, conn, finish_send)
589
+
590
+ def accept(self, listener):
591
+ self._register_with_iocp(listener)
592
+ conn = self._get_accept_socket(listener.family)
593
+ ov = _overlapped.Overlapped(NULL)
594
+ ov.AcceptEx(listener.fileno(), conn.fileno())
595
+
596
+ def finish_accept(trans, key, ov):
597
+ ov.getresult()
598
+ # Use SO_UPDATE_ACCEPT_CONTEXT so getsockname() etc work.
599
+ buf = struct.pack('@P', listener.fileno())
600
+ conn.setsockopt(socket.SOL_SOCKET,
601
+ _overlapped.SO_UPDATE_ACCEPT_CONTEXT, buf)
602
+ conn.settimeout(listener.gettimeout())
603
+ return conn, conn.getpeername()
604
+
605
+ async def accept_coro(future, conn):
606
+ # Coroutine closing the accept socket if the future is cancelled
607
+ try:
608
+ await future
609
+ except exceptions.CancelledError:
610
+ conn.close()
611
+ raise
612
+
613
+ future = self._register(ov, listener, finish_accept)
614
+ coro = accept_coro(future, conn)
615
+ tasks.ensure_future(coro, loop=self._loop)
616
+ return future
617
+
618
+ def connect(self, conn, address):
619
+ if conn.type == socket.SOCK_DGRAM:
620
+ # WSAConnect will complete immediately for UDP sockets so we don't
621
+ # need to register any IOCP operation
622
+ _overlapped.WSAConnect(conn.fileno(), address)
623
+ fut = self._loop.create_future()
624
+ fut.set_result(None)
625
+ return fut
626
+
627
+ self._register_with_iocp(conn)
628
+ # The socket needs to be locally bound before we call ConnectEx().
629
+ try:
630
+ _overlapped.BindLocal(conn.fileno(), conn.family)
631
+ except OSError as e:
632
+ if e.winerror != errno.WSAEINVAL:
633
+ raise
634
+ # Probably already locally bound; check using getsockname().
635
+ if conn.getsockname()[1] == 0:
636
+ raise
637
+ ov = _overlapped.Overlapped(NULL)
638
+ ov.ConnectEx(conn.fileno(), address)
639
+
640
+ def finish_connect(trans, key, ov):
641
+ ov.getresult()
642
+ # Use SO_UPDATE_CONNECT_CONTEXT so getsockname() etc work.
643
+ conn.setsockopt(socket.SOL_SOCKET,
644
+ _overlapped.SO_UPDATE_CONNECT_CONTEXT, 0)
645
+ return conn
646
+
647
+ return self._register(ov, conn, finish_connect)
648
+
649
+ def sendfile(self, sock, file, offset, count):
650
+ self._register_with_iocp(sock)
651
+ ov = _overlapped.Overlapped(NULL)
652
+ offset_low = offset & 0xffff_ffff
653
+ offset_high = (offset >> 32) & 0xffff_ffff
654
+ ov.TransmitFile(sock.fileno(),
655
+ msvcrt.get_osfhandle(file.fileno()),
656
+ offset_low, offset_high,
657
+ count, 0, 0)
658
+
659
+ def finish_sendfile(trans, key, ov):
660
+ try:
661
+ return ov.getresult()
662
+ except OSError as exc:
663
+ if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
664
+ _overlapped.ERROR_OPERATION_ABORTED):
665
+ raise ConnectionResetError(*exc.args)
666
+ else:
667
+ raise
668
+ return self._register(ov, sock, finish_sendfile)
669
+
670
+ def accept_pipe(self, pipe):
671
+ self._register_with_iocp(pipe)
672
+ ov = _overlapped.Overlapped(NULL)
673
+ connected = ov.ConnectNamedPipe(pipe.fileno())
674
+
675
+ if connected:
676
+ # ConnectNamePipe() failed with ERROR_PIPE_CONNECTED which means
677
+ # that the pipe is connected. There is no need to wait for the
678
+ # completion of the connection.
679
+ return self._result(pipe)
680
+
681
+ def finish_accept_pipe(trans, key, ov):
682
+ ov.getresult()
683
+ return pipe
684
+
685
+ return self._register(ov, pipe, finish_accept_pipe)
686
+
687
+ async def connect_pipe(self, address):
688
+ delay = CONNECT_PIPE_INIT_DELAY
689
+ while True:
690
+ # Unfortunately there is no way to do an overlapped connect to
691
+ # a pipe. Call CreateFile() in a loop until it doesn't fail with
692
+ # ERROR_PIPE_BUSY.
693
+ try:
694
+ handle = _overlapped.ConnectPipe(address)
695
+ break
696
+ except OSError as exc:
697
+ if exc.winerror != _overlapped.ERROR_PIPE_BUSY:
698
+ raise
699
+
700
+ # ConnectPipe() failed with ERROR_PIPE_BUSY: retry later
701
+ delay = min(delay * 2, CONNECT_PIPE_MAX_DELAY)
702
+ await tasks.sleep(delay)
703
+
704
+ return windows_utils.PipeHandle(handle)
705
+
706
+ def wait_for_handle(self, handle, timeout=None):
707
+ """Wait for a handle.
708
+
709
+ Return a Future object. The result of the future is True if the wait
710
+ completed, or False if the wait did not complete (on timeout).
711
+ """
712
+ return self._wait_for_handle(handle, timeout, False)
713
+
714
+ def _wait_cancel(self, event, done_callback):
715
+ fut = self._wait_for_handle(event, None, True)
716
+ # add_done_callback() cannot be used because the wait may only complete
717
+ # in IocpProactor.close(), while the event loop is not running.
718
+ fut._done_callback = done_callback
719
+ return fut
720
+
721
+ def _wait_for_handle(self, handle, timeout, _is_cancel):
722
+ self._check_closed()
723
+
724
+ if timeout is None:
725
+ ms = _winapi.INFINITE
726
+ else:
727
+ # RegisterWaitForSingleObject() has a resolution of 1 millisecond,
728
+ # round away from zero to wait *at least* timeout seconds.
729
+ ms = math.ceil(timeout * 1e3)
730
+
731
+ # We only create ov so we can use ov.address as a key for the cache.
732
+ ov = _overlapped.Overlapped(NULL)
733
+ wait_handle = _overlapped.RegisterWaitWithQueue(
734
+ handle, self._iocp, ov.address, ms)
735
+ if _is_cancel:
736
+ f = _WaitCancelFuture(ov, handle, wait_handle, loop=self._loop)
737
+ else:
738
+ f = _WaitHandleFuture(ov, handle, wait_handle, self,
739
+ loop=self._loop)
740
+ if f._source_traceback:
741
+ del f._source_traceback[-1]
742
+
743
+ def finish_wait_for_handle(trans, key, ov):
744
+ # Note that this second wait means that we should only use
745
+ # this with handles types where a successful wait has no
746
+ # effect. So events or processes are all right, but locks
747
+ # or semaphores are not. Also note if the handle is
748
+ # signalled and then quickly reset, then we may return
749
+ # False even though we have not timed out.
750
+ return f._poll()
751
+
752
+ self._cache[ov.address] = (f, ov, 0, finish_wait_for_handle)
753
+ return f
754
+
755
+ def _register_with_iocp(self, obj):
756
+ # To get notifications of finished ops on this objects sent to the
757
+ # completion port, were must register the handle.
758
+ if obj not in self._registered:
759
+ self._registered.add(obj)
760
+ _overlapped.CreateIoCompletionPort(obj.fileno(), self._iocp, 0, 0)
761
+ # XXX We could also use SetFileCompletionNotificationModes()
762
+ # to avoid sending notifications to completion port of ops
763
+ # that succeed immediately.
764
+
765
+ def _register(self, ov, obj, callback):
766
+ self._check_closed()
767
+
768
+ # Return a future which will be set with the result of the
769
+ # operation when it completes. The future's value is actually
770
+ # the value returned by callback().
771
+ f = _OverlappedFuture(ov, loop=self._loop)
772
+ if f._source_traceback:
773
+ del f._source_traceback[-1]
774
+ if not ov.pending:
775
+ # The operation has completed, so no need to postpone the
776
+ # work. We cannot take this short cut if we need the
777
+ # NumberOfBytes, CompletionKey values returned by
778
+ # PostQueuedCompletionStatus().
779
+ try:
780
+ value = callback(None, None, ov)
781
+ except OSError as e:
782
+ f.set_exception(e)
783
+ else:
784
+ f.set_result(value)
785
+ # Even if GetOverlappedResult() was called, we have to wait for the
786
+ # notification of the completion in GetQueuedCompletionStatus().
787
+ # Register the overlapped operation to keep a reference to the
788
+ # OVERLAPPED object, otherwise the memory is freed and Windows may
789
+ # read uninitialized memory.
790
+
791
+ # Register the overlapped operation for later. Note that
792
+ # we only store obj to prevent it from being garbage
793
+ # collected too early.
794
+ self._cache[ov.address] = (f, ov, obj, callback)
795
+ return f
796
+
797
+ def _unregister(self, ov):
798
+ """Unregister an overlapped object.
799
+
800
+ Call this method when its future has been cancelled. The event can
801
+ already be signalled (pending in the proactor event queue). It is also
802
+ safe if the event is never signalled (because it was cancelled).
803
+ """
804
+ self._check_closed()
805
+ self._unregistered.append(ov)
806
+
807
+ def _get_accept_socket(self, family):
808
+ s = socket.socket(family)
809
+ s.settimeout(0)
810
+ return s
811
+
812
+ def _poll(self, timeout=None):
813
+ if timeout is None:
814
+ ms = INFINITE
815
+ elif timeout < 0:
816
+ raise ValueError("negative timeout")
817
+ else:
818
+ # GetQueuedCompletionStatus() has a resolution of 1 millisecond,
819
+ # round away from zero to wait *at least* timeout seconds.
820
+ ms = math.ceil(timeout * 1e3)
821
+ if ms >= INFINITE:
822
+ raise ValueError("timeout too big")
823
+
824
+ while True:
825
+ status = _overlapped.GetQueuedCompletionStatus(self._iocp, ms)
826
+ if status is None:
827
+ break
828
+ ms = 0
829
+
830
+ err, transferred, key, address = status
831
+ try:
832
+ f, ov, obj, callback = self._cache.pop(address)
833
+ except KeyError:
834
+ if self._loop.get_debug():
835
+ self._loop.call_exception_handler({
836
+ 'message': ('GetQueuedCompletionStatus() returned an '
837
+ 'unexpected event'),
838
+ 'status': ('err=%s transferred=%s key=%#x address=%#x'
839
+ % (err, transferred, key, address)),
840
+ })
841
+
842
+ # key is either zero, or it is used to return a pipe
843
+ # handle which should be closed to avoid a leak.
844
+ if key not in (0, _overlapped.INVALID_HANDLE_VALUE):
845
+ _winapi.CloseHandle(key)
846
+ continue
847
+
848
+ if obj in self._stopped_serving:
849
+ f.cancel()
850
+ # Don't call the callback if _register() already read the result or
851
+ # if the overlapped has been cancelled
852
+ elif not f.done():
853
+ try:
854
+ value = callback(transferred, key, ov)
855
+ except OSError as e:
856
+ f.set_exception(e)
857
+ self._results.append(f)
858
+ else:
859
+ f.set_result(value)
860
+ self._results.append(f)
861
+ finally:
862
+ f = None
863
+
864
+ # Remove unregistered futures
865
+ for ov in self._unregistered:
866
+ self._cache.pop(ov.address, None)
867
+ self._unregistered.clear()
868
+
869
+ def _stop_serving(self, obj):
870
+ # obj is a socket or pipe handle. It will be closed in
871
+ # BaseProactorEventLoop._stop_serving() which will make any
872
+ # pending operations fail quickly.
873
+ self._stopped_serving.add(obj)
874
+
875
+ def close(self):
876
+ if self._iocp is None:
877
+ # already closed
878
+ return
879
+
880
+ # Cancel remaining registered operations.
881
+ for fut, ov, obj, callback in list(self._cache.values()):
882
+ if fut.cancelled():
883
+ # Nothing to do with cancelled futures
884
+ pass
885
+ elif isinstance(fut, _WaitCancelFuture):
886
+ # _WaitCancelFuture must not be cancelled
887
+ pass
888
+ else:
889
+ try:
890
+ fut.cancel()
891
+ except OSError as exc:
892
+ if self._loop is not None:
893
+ context = {
894
+ 'message': 'Cancelling a future failed',
895
+ 'exception': exc,
896
+ 'future': fut,
897
+ }
898
+ if fut._source_traceback:
899
+ context['source_traceback'] = fut._source_traceback
900
+ self._loop.call_exception_handler(context)
901
+
902
+ # Wait until all cancelled overlapped complete: don't exit with running
903
+ # overlapped to prevent a crash. Display progress every second if the
904
+ # loop is still running.
905
+ msg_update = 1.0
906
+ start_time = time.monotonic()
907
+ next_msg = start_time + msg_update
908
+ while self._cache:
909
+ if next_msg <= time.monotonic():
910
+ logger.debug('%r is running after closing for %.1f seconds',
911
+ self, time.monotonic() - start_time)
912
+ next_msg = time.monotonic() + msg_update
913
+
914
+ # handle a few events, or timeout
915
+ self._poll(msg_update)
916
+
917
+ self._results = []
918
+
919
+ _winapi.CloseHandle(self._iocp)
920
+ self._iocp = None
921
+
922
+ def __del__(self):
923
+ self.close()
924
+
925
+
926
+ class _WindowsSubprocessTransport(base_subprocess.BaseSubprocessTransport):
927
+
928
+ def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
929
+ self._proc = windows_utils.Popen(
930
+ args, shell=shell, stdin=stdin, stdout=stdout, stderr=stderr,
931
+ bufsize=bufsize, **kwargs)
932
+
933
+ def callback(f):
934
+ returncode = self._proc.poll()
935
+ self._process_exited(returncode)
936
+
937
+ f = self._loop._proactor.wait_for_handle(int(self._proc._handle))
938
+ f.add_done_callback(callback)
939
+
940
+
941
+ SelectorEventLoop = _WindowsSelectorEventLoop
942
+
943
+
944
+ class WindowsSelectorEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
945
+ _loop_factory = SelectorEventLoop
946
+
947
+
948
+ class WindowsProactorEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
949
+ _loop_factory = ProactorEventLoop
950
+
951
+
952
+ DefaultEventLoopPolicy = WindowsProactorEventLoopPolicy
shared/package-files/41/4196267074d3418142057b3fd8ee01f70773765821a3b706997853761e364686/_cast_Int_ops.h ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <string_view>
6
+ #include <tuple>
7
+ #include <vector>
8
+
9
+ // Forward declarations of any types needed in the operator signatures.
10
+ // We can't directly include these classes because it will cause circular include dependencies.
11
+ // This file is included by TensorBody.h, which defines the Tensor class.
12
+ #include <ATen/core/ATen_fwd.h>
13
+
14
+ namespace at {
15
+ namespace _ops {
16
+
17
+
18
+ struct TORCH_API _cast_Int {
19
+ using schema = at::Tensor (const at::Tensor &, bool);
20
+ using ptr_schema = schema*;
21
+ // See Note [static constexpr char* members for windows NVCC]
22
+ static constexpr const char* name = "aten::_cast_Int";
23
+ static constexpr const char* overload_name = "";
24
+ static constexpr const char* schema_str = "_cast_Int(Tensor self, bool non_blocking=False) -> Tensor";
25
+ static at::Tensor call(const at::Tensor & self, bool non_blocking);
26
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, bool non_blocking);
27
+ };
28
+
29
+ }} // namespace at::_ops
shared/package-files/41/41999bc58f9f7203eeb1e60b9ca54316ca07ea6e7b0a8b2fcb85bb9788c8a96c/plotgrid.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from sympy.external import import_module
3
+ import sympy.plotting.backends.base_backend as base_backend
4
+
5
+
6
+ # N.B.
7
+ # When changing the minimum module version for matplotlib, please change
8
+ # the same in the `SymPyDocTestFinder`` in `sympy/testing/runtests.py`
9
+
10
+
11
+ __doctest_requires__ = {
12
+ ("PlotGrid",): ["matplotlib"],
13
+ }
14
+
15
+
16
+ class PlotGrid:
17
+ """This class helps to plot subplots from already created SymPy plots
18
+ in a single figure.
19
+
20
+ Examples
21
+ ========
22
+
23
+ .. plot::
24
+ :context: close-figs
25
+ :format: doctest
26
+ :include-source: True
27
+
28
+ >>> from sympy import symbols
29
+ >>> from sympy.plotting import plot, plot3d, PlotGrid
30
+ >>> x, y = symbols('x, y')
31
+ >>> p1 = plot(x, x**2, x**3, (x, -5, 5))
32
+ >>> p2 = plot((x**2, (x, -6, 6)), (x, (x, -5, 5)))
33
+ >>> p3 = plot(x**3, (x, -5, 5))
34
+ >>> p4 = plot3d(x*y, (x, -5, 5), (y, -5, 5))
35
+
36
+ Plotting vertically in a single line:
37
+
38
+ .. plot::
39
+ :context: close-figs
40
+ :format: doctest
41
+ :include-source: True
42
+
43
+ >>> PlotGrid(2, 1, p1, p2)
44
+ PlotGrid object containing:
45
+ Plot[0]:Plot object containing:
46
+ [0]: cartesian line: x for x over (-5.0, 5.0)
47
+ [1]: cartesian line: x**2 for x over (-5.0, 5.0)
48
+ [2]: cartesian line: x**3 for x over (-5.0, 5.0)
49
+ Plot[1]:Plot object containing:
50
+ [0]: cartesian line: x**2 for x over (-6.0, 6.0)
51
+ [1]: cartesian line: x for x over (-5.0, 5.0)
52
+
53
+ Plotting horizontally in a single line:
54
+
55
+ .. plot::
56
+ :context: close-figs
57
+ :format: doctest
58
+ :include-source: True
59
+
60
+ >>> PlotGrid(1, 3, p2, p3, p4)
61
+ PlotGrid object containing:
62
+ Plot[0]:Plot object containing:
63
+ [0]: cartesian line: x**2 for x over (-6.0, 6.0)
64
+ [1]: cartesian line: x for x over (-5.0, 5.0)
65
+ Plot[1]:Plot object containing:
66
+ [0]: cartesian line: x**3 for x over (-5.0, 5.0)
67
+ Plot[2]:Plot object containing:
68
+ [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
69
+
70
+ Plotting in a grid form:
71
+
72
+ .. plot::
73
+ :context: close-figs
74
+ :format: doctest
75
+ :include-source: True
76
+
77
+ >>> PlotGrid(2, 2, p1, p2, p3, p4)
78
+ PlotGrid object containing:
79
+ Plot[0]:Plot object containing:
80
+ [0]: cartesian line: x for x over (-5.0, 5.0)
81
+ [1]: cartesian line: x**2 for x over (-5.0, 5.0)
82
+ [2]: cartesian line: x**3 for x over (-5.0, 5.0)
83
+ Plot[1]:Plot object containing:
84
+ [0]: cartesian line: x**2 for x over (-6.0, 6.0)
85
+ [1]: cartesian line: x for x over (-5.0, 5.0)
86
+ Plot[2]:Plot object containing:
87
+ [0]: cartesian line: x**3 for x over (-5.0, 5.0)
88
+ Plot[3]:Plot object containing:
89
+ [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
90
+
91
+ """
92
+ def __init__(self, nrows, ncolumns, *args, show=True, size=None, **kwargs):
93
+ """
94
+ Parameters
95
+ ==========
96
+
97
+ nrows :
98
+ The number of rows that should be in the grid of the
99
+ required subplot.
100
+ ncolumns :
101
+ The number of columns that should be in the grid
102
+ of the required subplot.
103
+
104
+ nrows and ncolumns together define the required grid.
105
+
106
+ Arguments
107
+ =========
108
+
109
+ A list of predefined plot objects entered in a row-wise sequence
110
+ i.e. plot objects which are to be in the top row of the required
111
+ grid are written first, then the second row objects and so on
112
+
113
+ Keyword arguments
114
+ =================
115
+
116
+ show : Boolean
117
+ The default value is set to ``True``. Set show to ``False`` and
118
+ the function will not display the subplot. The returned instance
119
+ of the ``PlotGrid`` class can then be used to save or display the
120
+ plot by calling the ``save()`` and ``show()`` methods
121
+ respectively.
122
+ size : (float, float), optional
123
+ A tuple in the form (width, height) in inches to specify the size of
124
+ the overall figure. The default value is set to ``None``, meaning
125
+ the size will be set by the default backend.
126
+ """
127
+ self.matplotlib = import_module('matplotlib',
128
+ import_kwargs={'fromlist': ['pyplot', 'cm', 'collections']},
129
+ min_module_version='1.1.0', catch=(RuntimeError,))
130
+ self.nrows = nrows
131
+ self.ncolumns = ncolumns
132
+ self._series = []
133
+ self._fig = None
134
+ self.args = args
135
+ for arg in args:
136
+ self._series.append(arg._series)
137
+ self.size = size
138
+ if show and self.matplotlib:
139
+ self.show()
140
+
141
+ def _create_figure(self):
142
+ gs = self.matplotlib.gridspec.GridSpec(self.nrows, self.ncolumns)
143
+ mapping = {}
144
+ c = 0
145
+ for i in range(self.nrows):
146
+ for j in range(self.ncolumns):
147
+ if c < len(self.args):
148
+ mapping[gs[i, j]] = self.args[c]
149
+ c += 1
150
+
151
+ kw = {} if not self.size else {"figsize": self.size}
152
+ self._fig = self.matplotlib.pyplot.figure(**kw)
153
+ for spec, p in mapping.items():
154
+ kw = ({"projection": "3d"} if (len(p._series) > 0 and
155
+ p._series[0].is_3D) else {})
156
+ cur_ax = self._fig.add_subplot(spec, **kw)
157
+ p._plotgrid_fig = self._fig
158
+ p._plotgrid_ax = cur_ax
159
+ p.process_series()
160
+
161
+ @property
162
+ def fig(self):
163
+ if not self._fig:
164
+ self._create_figure()
165
+ return self._fig
166
+
167
+ @property
168
+ def _backend(self):
169
+ return self
170
+
171
+ def close(self):
172
+ self.matplotlib.pyplot.close(self.fig)
173
+
174
+ def show(self):
175
+ if base_backend._show:
176
+ self.fig.tight_layout()
177
+ self.matplotlib.pyplot.show()
178
+ else:
179
+ self.close()
180
+
181
+ def save(self, path):
182
+ self.fig.savefig(path)
183
+
184
+ def __str__(self):
185
+ plot_strs = [('Plot[%d]:' % i) + str(plot)
186
+ for i, plot in enumerate(self.args)]
187
+
188
+ return 'PlotGrid object containing:\n' + '\n'.join(plot_strs)
shared/package-files/41/419e2f2664becb546976b555a200a0ec7b3dea4292a597c16ccfe6b9a2e18dd7/device_op_overrides.cpython-311.pyc ADDED
Binary file (4.1 kB). View file
 
shared/package-files/41/41a595b9f946c505054e855c5952336471bf6fc566e09246ea605954635ab0ad/test_vlen_array.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ try:
7
+ from numcodecs.vlen import VLenArray
8
+ except ImportError as e: # pragma: no cover
9
+ raise unittest.SkipTest("vlen-array not available") from e
10
+ from numcodecs.tests.common import (
11
+ assert_array_items_equal,
12
+ check_backwards_compatibility,
13
+ check_config,
14
+ check_encode_decode_array,
15
+ check_repr,
16
+ )
17
+
18
+ arrays = [
19
+ np.array([np.array([1, 2, 3]), np.array([4]), np.array([5, 6])] * 300, dtype=object),
20
+ np.array([np.array([1, 2, 3]), np.array([4]), np.array([5, 6])] * 300, dtype=object).reshape(
21
+ 90, 10
22
+ ),
23
+ ]
24
+
25
+
26
+ codecs = [
27
+ VLenArray('<i1'),
28
+ VLenArray('<i2'),
29
+ VLenArray('<i4'),
30
+ VLenArray('<i8'),
31
+ VLenArray('<u1'),
32
+ VLenArray('<u2'),
33
+ VLenArray('<u4'),
34
+ VLenArray('<u8'),
35
+ ]
36
+
37
+
38
+ def test_encode_decode():
39
+ for arr in arrays:
40
+ for codec in codecs:
41
+ check_encode_decode_array(arr, codec)
42
+
43
+
44
+ def test_config():
45
+ codec = VLenArray('<i8')
46
+ check_config(codec)
47
+
48
+
49
+ def test_repr():
50
+ check_repr("VLenArray(dtype='<i8')")
51
+
52
+
53
+ def test_backwards_compatibility():
54
+ check_backwards_compatibility(VLenArray.codec_id, arrays, codecs)
55
+
56
+
57
+ def test_encode_errors():
58
+ codec = VLenArray('<i8')
59
+ with pytest.raises(ValueError):
60
+ codec.encode('foo')
61
+ with pytest.raises(ValueError):
62
+ codec.encode(['foo', 'bar'])
63
+
64
+
65
+ def test_decode_errors():
66
+ codec = VLenArray('<i8')
67
+ with pytest.raises(TypeError):
68
+ codec.decode(1234)
69
+ # these should look like corrupt data
70
+ with pytest.raises(ValueError):
71
+ codec.decode(b'foo')
72
+ with pytest.raises(ValueError):
73
+ codec.decode(np.arange(2, 3, dtype='i4'))
74
+ with pytest.raises(ValueError):
75
+ codec.decode(np.arange(10, 20, dtype='i4'))
76
+ with pytest.raises(TypeError):
77
+ codec.decode('foo')
78
+
79
+ # test out parameter
80
+ enc = codec.encode(arrays[0])
81
+ with pytest.raises(TypeError):
82
+ codec.decode(enc, out=b'foo')
83
+ with pytest.raises(TypeError):
84
+ codec.decode(enc, out='foo')
85
+ with pytest.raises(TypeError):
86
+ codec.decode(enc, out=123)
87
+ with pytest.raises(ValueError):
88
+ codec.decode(enc, out=np.zeros(10, dtype='i4'))
89
+
90
+
91
+ def test_encode_none():
92
+ a = np.array([[1, 3], None, [4, 7]], dtype=object)
93
+ codec = VLenArray(int)
94
+ enc = codec.encode(a)
95
+ dec = codec.decode(enc)
96
+ expect = np.array([np.array([1, 3]), np.array([]), np.array([4, 7])], dtype=object)
97
+ assert_array_items_equal(expect, dec)
shared/package-files/41/41a607bad835178db0de3bce283f20896cb10ead4654172cf8aa58c6672ad70b/binary_cross_entropy.h ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+ #include <string_view>
18
+
19
+
20
+
21
+ #include <ATen/ops/binary_cross_entropy_ops.h>
22
+
23
+ namespace at {
24
+
25
+
26
+ // aten::binary_cross_entropy(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean) -> Tensor
27
+ inline at::Tensor binary_cross_entropy(const at::Tensor & self, const at::Tensor & target, const ::std::optional<at::Tensor> & weight={}, int64_t reduction=at::Reduction::Mean) {
28
+ return at::_ops::binary_cross_entropy::call(self, target, weight, reduction);
29
+ }
30
+
31
+ // aten::binary_cross_entropy.out(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!)
32
+ inline at::Tensor & binary_cross_entropy_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & target, const ::std::optional<at::Tensor> & weight={}, int64_t reduction=at::Reduction::Mean) {
33
+ return at::_ops::binary_cross_entropy_out::call(self, target, weight, reduction, out);
34
+ }
35
+ // aten::binary_cross_entropy.out(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!)
36
+ inline at::Tensor & binary_cross_entropy_outf(const at::Tensor & self, const at::Tensor & target, const ::std::optional<at::Tensor> & weight, int64_t reduction, at::Tensor & out) {
37
+ return at::_ops::binary_cross_entropy_out::call(self, target, weight, reduction, out);
38
+ }
39
+
40
+ }